@Override
 public IRegion getSubject(final ITextViewer textViewer, final int offset) {
   if (fScanner == null) {
     fScanner =
         (RHeuristicTokenScanner)
             LTK.getModelAdapter(getEditor().getModelTypeId(), RHeuristicTokenScanner.class);
   }
   try {
     final IDocument document = getEditor().getViewer().getDocument();
     fScanner.configure(document);
     final IRegion word = fScanner.findRWord(offset, false, true);
     if (word != null) {
       final ITypedRegion partition = fScanner.getPartition(word.getOffset());
       if (fScanner
               .getPartitioningConfig()
               .getDefaultPartitionConstraint()
               .matches(partition.getType())
           || partition.getType() == IRDocumentPartitions.R_STRING
           || partition.getType() == IRDocumentPartitions.R_QUOTED_SYMBOL) {
         return word;
       }
     }
   } catch (final Exception e) {
   }
   return new Region(offset, 0);
 }
 protected CompoundRegion[] getRegionsWithoutWhiteSpaces(
     IStructuredDocument model, IRegion reg, CSSCleanupStrategy stgy) {
   int start = reg.getOffset();
   int end = reg.getOffset() + reg.getLength() - 1;
   ArrayList list = new ArrayList();
   IStructuredDocumentRegion flatNode = model.getRegionAtCharacterOffset(start);
   while (flatNode != null && flatNode.getStartOffset() <= end) {
     ITextRegionList regionList = flatNode.getRegions();
     Iterator it = regionList.iterator();
     while (it.hasNext()) {
       ITextRegion region = (ITextRegion) it.next();
       if (flatNode.getStartOffset(region) < start) continue;
       if (end < flatNode.getStartOffset(region)) break;
       if (region.getType() != CSSRegionContexts.CSS_S
           || (isCleanup() && !stgy.isFormatSource())) // for
         // not
         // formatting
         // case
         // on
         // cleanup
         // action
         list.add(new CompoundRegion(flatNode, region));
     }
     flatNode = flatNode.getNext();
   }
   if (list.size() > 0) {
     CompoundRegion[] regions = new CompoundRegion[list.size()];
     list.toArray(regions);
     return regions;
   }
   return new CompoundRegion[0];
 }
Пример #3
0
  /**
   * Returns the indentation of the line <code>line</code> in <code>document</code>. The returned
   * string may contain pairs of leading slashes that are considered part of the indentation. The
   * space before the asterix in a javadoc-like comment is not considered part of the indentation.
   *
   * @param document the document
   * @param line the line
   * @return the indentation of <code>line</code> in <code>document</code>
   * @throws BadLocationException if the document is changed concurrently
   */
  private static String getCurrentIndent(IDocument document, int line) throws BadLocationException {
    IRegion region = document.getLineInformation(line);
    int from = region.getOffset();
    int endOffset = region.getOffset() + region.getLength();

    // go behind line comments
    int to = from;
    while (to < endOffset - 2 && document.get(to, 2).equals(SLASHES)) to += 2;

    while (to < endOffset) {
      char ch = document.getChar(to);
      if (!Character.isWhitespace(ch)) break;
      to++;
    }

    // don't count the space before javadoc like, asterix-style comment lines
    if (to > from && to < endOffset - 1 && document.get(to - 1, 2).equals(" *")) { // $NON-NLS-1$
      String type =
          TextUtilities.getContentType(document, IJavaPartitions.JAVA_PARTITIONING, to, true);
      if (type.equals(IJavaPartitions.JAVA_DOC)
          || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) to--;
    }

    return document.get(from, to - from);
  }
Пример #4
0
  /**
   * Make all inside partitions join in one comment, in particular remove all enclosing comment
   * tokens of the inside partitions.
   *
   * @param commentArea comment area region
   * @param partition first partition
   * @param docExtension document
   * @param factory EditFactory
   * @param List of edits to update the document
   * @throws BadLocationException
   * @throws BadPartitioningException
   */
  private void handleInteriorPartition(
      IRegion commentArea,
      ITypedRegion partition,
      IDocumentExtension3 docExtension,
      Edit.EditFactory factory,
      List<Edit> edits)
      throws BadLocationException, BadPartitioningException {

    int commentAreaEnd = commentArea.getOffset() + commentArea.getLength();
    int prevPartitionEnd = -1;
    int partitionEnd = partition.getOffset() + partition.getLength();

    final int startCommentTokenLength = getCommentStart().length();
    final int endCommentTokenLength = getCommentEnd().length();

    while (partitionEnd <= commentAreaEnd) {
      if (partition.getType() == ICPartitions.C_MULTI_LINE_COMMENT
          || partition.getType() == ICPartitions.C_MULTI_LINE_DOC_COMMENT) {
        // already in a comment - remove start/end tokens
        edits.add(
            factory.createEdit(partition.getOffset(), startCommentTokenLength, "")); // $NON-NLS-1$
        edits.add(
            factory.createEdit(
                partitionEnd - endCommentTokenLength, endCommentTokenLength, "")); // $NON-NLS-1$
      }
      // advance to next partition
      prevPartitionEnd = partitionEnd;
      partition = docExtension.getPartition(ICPartitions.C_PARTITIONING, partitionEnd, false);
      partitionEnd = partition.getOffset() + partition.getLength();

      // break the loop if we get stuck and no advance was made
      if (partitionEnd <= prevPartitionEnd) break;
    }
  }
  /**
   * Computes the relevance to match the relevance values generated by the core content assistant.
   *
   * @return a sensible relevance value.
   */
  private int computeRelevance() {
    // see org.eclipse.jdt.internal.codeassist.RelevanceConstants
    final int R_DEFAULT = 0;
    final int R_INTERESTING = 5;
    final int R_CASE = 10;
    final int R_NON_RESTRICTED = 3;
    final int R_EXACT_NAME = 4;
    final int R_INLINE_TAG = 31;

    int base = R_DEFAULT + R_INTERESTING + R_NON_RESTRICTED;

    try {
      if (fContext instanceof DocumentTemplateContext) {
        DocumentTemplateContext templateContext = (DocumentTemplateContext) fContext;
        IDocument document = templateContext.getDocument();

        String content = document.get(fRegion.getOffset(), fRegion.getLength());
        if (content.length() > 0 && fTemplate.getName().startsWith(content)) base += R_CASE;
        if (fTemplate.getName().equalsIgnoreCase(content)) base += R_EXACT_NAME;
        if (fContext instanceof JavaDocContext) base += R_INLINE_TAG;
      }
    } catch (BadLocationException e) {
      // ignore - not a case sensitive match then
    }

    // see CompletionProposalCollector.computeRelevance
    // just under keywords, but better than packages
    final int TEMPLATE_RELEVANCE = 1;
    return base * 16 + TEMPLATE_RELEVANCE;
  }
Пример #6
0
  /**
   * Indents line <code>line</code> in <code>document</code> with <code>indent</code>. Leaves
   * leading comment signs alone.
   *
   * @param document the document
   * @param line the line
   * @param indent the indentation to insert
   * @param tabLength the length of a tab
   * @throws BadLocationException on concurrent document modification
   */
  private void addIndent(Document document, int line, CharSequence indent, int tabLength)
      throws BadLocationException {
    IRegion region = document.getLineInformation(line);
    int insert = region.getOffset();
    int endOffset = region.getOffset() + region.getLength();

    // Compute insert after all leading line comment markers
    int newInsert = insert;
    while (newInsert < endOffset - 2 && document.get(newInsert, 2).equals(LINE_COMMENT))
      newInsert += 2;

    // Heuristic to check whether it is commented code or just a comment
    if (newInsert > insert) {
      int whitespaceCount = 0;
      int i = newInsert;
      while (i < endOffset - 1) {
        char ch = document.get(i, 1).charAt(0);
        if (!Character.isWhitespace(ch)) break;
        whitespaceCount = whitespaceCount + computeVisualLength(ch, tabLength);
        i++;
      }

      if (whitespaceCount != 0 && whitespaceCount >= CodeFormatterUtil.getIndentWidth(fProject))
        insert = newInsert;
    }

    // Insert indent
    document.replace(insert, 0, indent.toString());
  }
  public void testNoDefaultLocaleForChangeAndRefresh() throws Throwable {
    VpeController controller =
        openInVpe(JsfAllTests.IMPORT_JSF_LOCALES_PROJECT_NAME, NO_DEFLOC_CHANGE_REFRESH_PAGE);
    nsIDOMDocument doc = controller.getXulRunnerEditor().getDOMDocument();

    nsIDOMElement localeText = doc.getElementById(LOCALE_TEXT_ID);
    String localizedText = getLocalizedText(localeText);
    assertTrue(
        "Text is '" + localizedText + "', but should be in 'de' locale",
        HELLO2_DE.equalsIgnoreCase(localizedText)); // $NON-NLS-1$ //$NON-NLS-2$
    /*
     * Change the locale
     */
    Element fViewElement =
        controller.getSourceBuilder().getSourceDocument().getElementById(FVIEW_ID);
    int offset = controller.getSourceBuilder().getPosition(fViewElement, 0, false);
    assertTrue(
        "Previous locale should be 'de'",
        "de"
            .equalsIgnoreCase(
                fViewElement.getAttribute("locale"))); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    IRegion reg =
        new FindReplaceDocumentAdapter(
                controller.getSourceBuilder().getStructuredTextViewer().getDocument())
            .find(offset, "de", true, true, false, false);
    controller
        .getSourceBuilder()
        .getStructuredTextViewer()
        .getDocument()
        .replace(reg.getOffset(), reg.getLength(), "en_GB");
    /*
     * Wait until new value is applied and children are refreshed.
     * Wait while all deferred events are processed
     */
    while (Display.getCurrent().readAndDispatch()) ;
    /*
     * Wait while all jobs including started through deferred events are ended
     */
    JobUtils.delay(VpeController.DEFAULT_UPDATE_DELAY_TIME * 4);
    TestUtil.waitForIdle();
    fViewElement = controller.getSourceBuilder().getSourceDocument().getElementById(FVIEW_ID);
    assertTrue(
        "Current locale should be 'en_GB'",
        "en_GB"
            .equalsIgnoreCase(
                fViewElement.getAttribute("locale"))); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    doc = controller.getXulRunnerEditor().getDOMDocument();
    localeText = doc.getElementById(LOCALE_TEXT_ID);
    localizedText = getLocalizedText(localeText);

    /*
     * Check the new localized message.
     */
    assertTrue(
        "Text is '" + localizedText + "', but should be in 'en_GB' locale",
        HELLO_EN_GB.equalsIgnoreCase(localizedText)); // $NON-NLS-1$ //$NON-NLS-2$
    closeEditors();
  }
  protected void copyIndentation(final IDocument d, final DocumentCommand c) {
    // CODE KOPIERT AUS SUPER-KLASSE DA DORT PRIVATE
    // == DefaultIndentLineAutoEditStrategy.autoIndentAfterNewLine(IDocument d, DocumentCommand c)

    if (c.offset == -1 || d.getLength() == 0) return;

    try {
      // find start of line
      int p = (c.offset == d.getLength() ? c.offset - 1 : c.offset);
      IRegion info = d.getLineInformationOfOffset(p);
      int start = info.getOffset();

      // find white spaces
      int end = findEndOfWhiteSpace(d, start, c.offset);

      StringBuffer buf = new StringBuffer(c.text);
      if (end > start) {
        // append to input
        buf.append(d.get(start, end - start));
      }

      c.text = buf.toString();

    } catch (BadLocationException excp) {
      // stop work
    }
  }
Пример #9
0
  @Override
  public void run() {
    ISearchQuery searchJob = null;

    ISelection selection = getSelection();
    if (selection instanceof IStructuredSelection) {
      Object object = ((IStructuredSelection) selection).getFirstElement();
      if (object instanceof ISourceReference) searchJob = createQuery((ISourceReference) object);
    } else if (selection instanceof ITextSelection) {
      ITextSelection selNode = (ITextSelection) selection;
      ICElement element = fEditor.getInputCElement();
      while (element != null && !(element instanceof ITranslationUnit))
        element = element.getParent();
      if (element != null) {
        if (selNode.getLength() == 0) {
          IDocument document = fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput());
          IRegion reg = CWordFinder.findWord(document, selNode.getOffset());
          selNode = new TextSelection(document, reg.getOffset(), reg.getLength());
        }
        searchJob = createQuery(element, selNode);
      }
    }

    if (searchJob == null) {
      showStatusLineMessage(CSearchMessages.CSearchOperation_operationUnavailable_message);
      return;
    }

    clearStatusLine();
    NewSearchUI.activateSearchResultView();
    NewSearchUI.runQueryInBackground(searchJob);
  }
 static IRegion getCurrentArgumentRegion(IDocument document, int loc, int index, int startOfArgs)
     throws BadLocationException {
   IRegion li = document.getLineInformationOfOffset(loc);
   int endOfLine = li.getOffset() + li.getLength();
   int offset = findCharCount(index, document, loc + startOfArgs, endOfLine, ",;", "", true) + 1;
   if (offset > 0 && document.getChar(offset) == ' ') {
     offset++;
   }
   int nextOffset =
       findCharCount(index + 1, document, loc + startOfArgs, endOfLine, ",;", "", true);
   int middleOffset = findCharCount(1, document, offset, nextOffset, "=", "", true) + 1;
   if (middleOffset > 0 && document.getChar(middleOffset) == '>') {
     middleOffset++;
   }
   while (middleOffset > 0 && document.getChar(middleOffset) == ' ') {
     middleOffset++;
   }
   if (middleOffset > offset && middleOffset < nextOffset) {
     offset = middleOffset;
   }
   if (nextOffset == -1) {
     nextOffset = offset;
   }
   return new Region(offset, nextOffset - offset);
 }
 /**
  * Returns the variable and function names at the current line, or <code>null</code> if none.
  *
  * @param part text editor
  * @param selection text selection
  * @return the variable and function names at the current line, or <code>null</code> if none. The
  *     array has two elements, the first is the variable name, the second is the function name.
  */
 protected String[] getVariableAndFunctionName(IWorkbenchPart part, ISelection selection) {
   ITextEditor editor = getEditor(part);
   if (editor != null && selection instanceof ITextSelection) {
     ITextSelection textSelection = (ITextSelection) selection;
     IDocumentProvider documentProvider = editor.getDocumentProvider();
     try {
       documentProvider.connect(this);
       IDocument document = documentProvider.getDocument(editor.getEditorInput());
       IRegion region = document.getLineInformationOfOffset(textSelection.getOffset());
       String string = document.get(region.getOffset(), region.getLength()).trim();
       if (string.startsWith("var ")) { // $NON-NLS-1$
         String varName = string.substring(4).trim();
         String fcnName =
             getFunctionName(
                 document, varName, document.getLineOfOffset(textSelection.getOffset()));
         return new String[] {varName, fcnName};
       }
     } catch (CoreException e) {
     } catch (BadLocationException e) {
     } finally {
       documentProvider.disconnect(this);
     }
   }
   return null;
 }
Пример #12
0
  /**
   * Determines whether each line is prefixed by one of the prefixes.
   *
   * @param startLine Start line in document
   * @param endLine End line in document
   * @param prefixes Possible comment prefixes
   * @param document The document
   * @return <code>true</code> iff each line from <code>startLine</code> to and including <code>
   *     endLine</code> is prepended by one of the <code>prefixes</code>, ignoring whitespace at the
   *     begin of line
   */
  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
      // FIXME			Activator.getPlugin().log(x);
    }

    return false;
  }
Пример #13
0
 private String getRelativeIndent(int offset) {
   int indent = getStringOrCommentIndent(offset);
   try {
     IRegion lineInfo = document.getLineInformationOfOffset(offset);
     StringBuilder result = new StringBuilder();
     int lineOffset = lineInfo.getOffset();
     for (int i = lineOffset; i < lineOffset + indent; i++) {
       char ch = document.getChar(i);
       if (ch != ' ' && ch != '\t') {
         return "";
       }
     }
     for (int i = lineOffset + indent; ; ) {
       char ch = document.getChar(i++);
       if (ch == ' ' || ch == '\t') {
         result.append(ch);
       } else {
         break;
       }
     }
     return result.toString();
   } catch (BadLocationException e) {
     e.printStackTrace();
     return "";
   }
 }
Пример #14
0
  private static void loadRegions(List<TestRegion> regionList, IDocument document)
      throws BadLocationException {
    FindReplaceDocumentAdapter adapter = new FindReplaceDocumentAdapter(document);
    // IRegion region = adapter.find(0, "{", true, true, false, false);
    // if(region == null)
    IRegion region = new Region(0, 0);
    for (TestRegion testRegion : regionList) {
      IRegion newRegion =
          adapter.find(
              region.getOffset() + region.getLength(),
              testRegion.regionText,
              true,
              true,
              false,
              false);
      if (newRegion != null) {
        testRegion.region = newRegion;
        region = newRegion;
      } else fail("Can not find string - " + testRegion.regionText);
    }

    for (int i = regionList.size() - 1; i >= 0; i--) {
      TestRegion r = regionList.get(i);
      if (r.hyperlinks.size() == 0) regionList.remove(r);
    }
  }
  public void collectOccurrenceMatches(
      IJavaScriptElement element, IDocument document, Collection resultingMatches) {
    HashMap lineToLineElement = new HashMap();

    for (Iterator iter = fResult.iterator(); iter.hasNext(); ) {
      ASTNode node = (ASTNode) iter.next();
      int startPosition = node.getStartPosition();
      int length = node.getLength();
      try {
        boolean isException = node == fSelectedName;
        int line = document.getLineOfOffset(startPosition);
        Integer lineInteger = new Integer(line);
        ExceptionOccurrencesGroupKey groupKey =
            (ExceptionOccurrencesGroupKey) lineToLineElement.get(lineInteger);
        if (groupKey == null) {
          IRegion region = document.getLineInformation(line);
          String lineContents = document.get(region.getOffset(), region.getLength()).trim();
          groupKey = new ExceptionOccurrencesGroupKey(element, line, lineContents, isException);
          lineToLineElement.put(lineInteger, groupKey);
        } else if (isException) {
          // the line with the target exception always has the exception icon:
          groupKey.setException(true);
        }
        Match match = new Match(groupKey, startPosition, length);
        resultingMatches.add(match);
      } catch (BadLocationException e) {
        // nothing
      }
    }
  }
Пример #16
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;
  }
Пример #17
0
  /* (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;
  }
Пример #18
0
  public void run(IAction action) {
    PyEdit pyEdit = getPyEdit();
    PySelection ps = new PySelection(pyEdit);
    if (ps.getSelLength() != 0) {
      return;
    }
    try {
      IDocument doc = ps.getDoc();
      char c = doc.getChar(ps.getAbsoluteCursorOffset() - 1);
      boolean opening = StringUtils.isOpeningPeer(c);
      boolean closing = org.python.pydev.shared_core.string.StringUtils.isClosingPeer(c);

      if (opening || closing) {
        PythonPairMatcher matcher = new PythonPairMatcher();
        IRegion match = matcher.match(doc, ps.getAbsoluteCursorOffset());
        if (match != null) {
          if (closing) {
            pyEdit.setSelection(match.getOffset() + 1, 0);
          } else { // opening
            pyEdit.setSelection(match.getOffset() + match.getLength(), 0);
          }
        }
      }
    } catch (BadLocationException e) {
      return;
    }
  }
  public static int collectQuickFixableAnnotations(
      ITextEditor editor,
      int invocationLocation,
      boolean goToClosest,
      ArrayList resultingAnnotations)
      throws BadLocationException {
    IAnnotationModel model =
        JavaScriptUI.getDocumentProvider().getAnnotationModel(editor.getEditorInput());
    if (model == null) {
      return invocationLocation;
    }

    ensureUpdatedAnnotations(editor);

    Iterator iter = model.getAnnotationIterator();
    if (goToClosest) {
      IRegion lineInfo = getRegionOfInterest(editor, invocationLocation);
      if (lineInfo == null) {
        return invocationLocation;
      }
      int rangeStart = lineInfo.getOffset();
      int rangeEnd = rangeStart + lineInfo.getLength();

      ArrayList allAnnotations = new ArrayList();
      ArrayList allPositions = new ArrayList();
      int bestOffset = Integer.MAX_VALUE;
      while (iter.hasNext()) {
        Annotation annot = (Annotation) iter.next();
        if (JavaCorrectionProcessor.isQuickFixableType(annot)) {
          Position pos = model.getPosition(annot);
          if (pos != null && isInside(pos.offset, rangeStart, rangeEnd)) { // inside our range?
            allAnnotations.add(annot);
            allPositions.add(pos);
            bestOffset = processAnnotation(annot, pos, invocationLocation, bestOffset);
          }
        }
      }
      if (bestOffset == Integer.MAX_VALUE) {
        return invocationLocation;
      }
      for (int i = 0; i < allPositions.size(); i++) {
        Position pos = (Position) allPositions.get(i);
        if (isInside(bestOffset, pos.offset, pos.offset + pos.length)) {
          resultingAnnotations.add(allAnnotations.get(i));
        }
      }
      return bestOffset;
    } else {
      while (iter.hasNext()) {
        Annotation annot = (Annotation) iter.next();
        if (JavaCorrectionProcessor.isQuickFixableType(annot)) {
          Position pos = model.getPosition(annot);
          if (pos != null && isInside(invocationLocation, pos.offset, pos.offset + pos.length)) {
            resultingAnnotations.add(annot);
          }
        }
      }
      return invocationLocation;
    }
  }
  @Override
  public Object getHoverInfo2(final ITextViewer textViewer, final IRegion hoverRegion) {
    final ISourceEditor editor = getEditor();
    if (editor != null && ensureHover()) {
      try {
        final String contentType =
            (hoverRegion instanceof TypedRegion)
                ? ((TypedRegion) hoverRegion).getType()
                : TextUtils.getContentType(
                    editor.getViewer().getDocument(),
                    editor.getDocumentContentInfo(),
                    hoverRegion.getOffset(),
                    hoverRegion.getLength() == 0);

        final AssistInvocationContext context =
            createContext(hoverRegion, contentType, new NullProgressMonitor());
        if (context != null) {
          return this.hover.getHoverInfo(context);
        }
      } catch (final Exception e) {
        StatusManager.getManager()
            .handle(
                new Status(
                    IStatus.ERROR,
                    LTKUIPlugin.PLUGIN_ID,
                    NLS.bind(
                        "An error occurred when preparing the information hover ''{0}'' (mouse).",
                        this.descriptor.getName()),
                    e));
      }
    }
    return null;
  }
Пример #21
0
 /**
  * Returns the position of the first non whitespace char in the current line.
  *
  * @param doc
  * @param cursorOffset
  * @return position of the first character of the line (returned as an absolute offset)
  * @throws BadLocationException
  */
 public static int getFirstCharPosition(IDocument doc, int cursorOffset)
     throws BadLocationException {
   IRegion region;
   region = doc.getLineInformationOfOffset(cursorOffset);
   int offset = region.getOffset();
   return offset + getFirstCharRelativePosition(doc, cursorOffset);
 }
  private void doJSPELHyperlinkTestForELInTagBodyTest(
      String pageName, String template, String editorName) throws BadLocationException {
    IEditorPart editor = WorkbenchUtils.openEditor(pageName);
    assertTrue(editor instanceof JSPMultiPageEditor);
    JSPMultiPageEditor jspMultyPageEditor = (JSPMultiPageEditor) editor;
    ISourceViewer viewer = jspMultyPageEditor.getSourceEditor().getTextViewer();
    assertNotNull("Viewer couldn't be found for " + pageName, viewer);
    IDocument document = viewer.getDocument();
    IRegion reg =
        new FindReplaceDocumentAdapter(document).find(0, template, true, true, false, false);
    assertNotNull("Text: " + template + " not found", reg);

    IHyperlink[] links =
        elHyperlinkDetector.detectHyperlinks(
            viewer, new Region(reg.getOffset() + reg.getLength() - 1, 0), true);

    assertNotNull("Hyperlinks for EL:#{" + template + "} are not found", links);

    assertTrue("Hyperlinks for EL: #{" + template + "} are not found", links.length != 0);

    boolean found = false;
    for (IHyperlink link : links) {
      assertNotNull(link.toString());

      link.open();

      IEditorPart resultEditor =
          PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
      if (editorName.equals(resultEditor.getTitle())) {
        found = true;
        return;
      }
    }
    assertTrue("OpenOn have not opened " + editorName + " editor", found);
  }
Пример #23
0
  /**
   * @param doc
   * @param region
   * @return
   * @throws BadLocationException
   */
  public static int getFirstCharRelativePosition(IDocument doc, IRegion region)
      throws BadLocationException {
    int offset = region.getOffset();
    String src = doc.get(offset, region.getLength());

    return getFirstCharPosition(src);
  }
Пример #24
0
 /*
  * @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
     }
   }
 }
Пример #25
0
  /**
   * Calculates the common scope between the end of one line and the beginning of the next.
   *
   * @param document
   * @param line
   * @param endOfLineScope
   * @return
   * @throws BadLocationException
   */
  private String getScope(IDocument document, int line, String endOfLineScope)
      throws BadLocationException {
    // if this is the last line, just use the scope at the end of it.
    int lines = document.getNumberOfLines();
    if (line + 1 >= lines) {
      return endOfLineScope;
    }

    // now grab the scope at the beginning of the next line...
    IRegion nextLine = document.getLineInformation(line + 1);
    // If the next line is empty, take our end of line scope
    if (nextLine.getLength() == 0) {
      return endOfLineScope;
    }
    String startOfNextLineScope =
        getScopeManager().getScopeAtOffset(document, nextLine.getOffset());

    // Calculate the common prefix between the two!
    StringBuilder builder = new StringBuilder();
    int length = Math.min(endOfLineScope.length(), startOfNextLineScope.length());
    for (int i = 0; i < length; i++) {
      char c = endOfLineScope.charAt(i);
      char o = startOfNextLineScope.charAt(i);
      if (c == o) {
        builder.append(c);
      }
    }
    return builder.toString();
  }
  /**
   * 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);
  }
Пример #27
0
  /**
   * Checks if the angular bracket at <code>offset</code> is a type parameter bracket.
   *
   * @param offset the offset of the opening bracket
   * @param document the document
   * @param scanner a java heuristic scanner on <code>document</code>
   * @return <code>true</code> if the bracket is part of a type parameter, <code>false</code>
   *     otherwise
   * @since 3.1
   */
  private boolean isTypeParameterBracket(
      int offset, IDocument document, PHPHeuristicScanner scanner) {
    /*
     * type parameter come after braces (closing or opening), semicolons, or
     * after a Type name (heuristic: starts with capital character, or after
     * a modifier keyword in a method declaration (visibility, static,
     * synchronized, final)
     */

    try {
      final IRegion line = document.getLineInformationOfOffset(offset);

      final int prevToken = scanner.previousToken(offset - 1, line.getOffset());
      final int prevTokenOffset = scanner.getPosition() + 1;
      final String previous =
          prevToken == Symbols.TokenEOF
              ? null
              : document.get(prevTokenOffset, offset - prevTokenOffset).trim();

      if (prevToken == Symbols.TokenLBRACE
          || prevToken == Symbols.TokenRBRACE
          || prevToken == Symbols.TokenSEMICOLON
          || prevToken == Symbols.TokenSYNCHRONIZED
          || prevToken == Symbols.TokenSTATIC
          || (prevToken == Symbols.TokenIDENT && isTypeParameterIntroducer(previous))
          || prevToken == Symbols.TokenEOF) {
        return true;
      }
    } catch (final BadLocationException e) {
      return false;
    }

    return false;
  }
  private void appendContent(
      IDocument text,
      int startOffset,
      int endOffset,
      StringBuilder buf,
      boolean surroundLinesOnly) {
    try {
      int startLine = text.getLineOfOffset(startOffset);
      int endLine = text.getLineOfOffset(endOffset);

      boolean dotsAdded = false;
      if (surroundLinesOnly && startOffset == 0) { // No surround lines for the top no-change range
        startLine = Math.max(endLine - surroundLines, 0);
        buf.append("...<br>"); // $NON-NLS-1$
        dotsAdded = true;
      }

      for (int i = startLine; i <= endLine; i++) {
        if (surroundLinesOnly) {
          if ((i - startLine > surroundLines) && (endLine - i > surroundLines)) {
            if (!dotsAdded) {
              buf.append("...<br>"); // $NON-NLS-1$
              dotsAdded = true;
            } else if (endOffset == text.getLength()) {
              return; // No surround lines for the bottom no-change range
            }
            continue;
          }
        }

        IRegion lineInfo = text.getLineInformation(i);
        int start = lineInfo.getOffset();
        int end = start + lineInfo.getLength();

        int from = Math.max(start, startOffset);
        int to = Math.min(end, endOffset);
        String content = text.get(from, to - from);
        if (surroundLinesOnly && from == start && Strings.containsOnlyWhitespaces(content)) {
          continue; // Ignore empty lines except when range started in the middle of a line
        }
        for (int k = 0; k < content.length(); k++) {
          char ch = content.charAt(k);
          if (ch == '<') {
            buf.append("&lt;"); // $NON-NLS-1$
          } else if (ch == '>') {
            buf.append("&gt;"); // $NON-NLS-1$
          } else {
            buf.append(ch);
          }
        }
        if (to == end
            && to != endOffset) { // New line when at the end of the line, and not end of range
          buf.append("<br>"); // $NON-NLS-1$
        }
      }
    } catch (BadLocationException e) {
      // Ignore.
    }
  }
Пример #29
0
 public static String getLineContentsToCursor(IDocument doc, int offset)
     throws BadLocationException {
   int lineOfOffset = doc.getLineOfOffset(offset);
   IRegion lineInformation = doc.getLineInformation(lineOfOffset);
   String lineToCursor =
       doc.get(lineInformation.getOffset(), offset - lineInformation.getOffset());
   return lineToCursor;
 }
Пример #30
0
  /**
   * @return the line where the cursor is (from the cursor position to the end of the line).
   * @throws BadLocationException
   */
  public String getLineContentsFromCursor(int offset) throws BadLocationException {
    int lineOfOffset = doc.getLineOfOffset(offset);
    IRegion lineInformation = doc.getLineInformation(lineOfOffset);

    String lineToCursor =
        doc.get(offset, lineInformation.getOffset() + lineInformation.getLength() - offset);
    return lineToCursor;
  }