Ejemplo n.º 1
0
  /**
   * Finds a word by specified offset and returns the region of word.
   *
   * @param source
   * @param offset
   * @return the region of found word
   */
  public static IRegion findWord(IDocument document, int offset) {

    int start = -2;
    int end = -1;

    try {
      int pos = offset;
      char c;

      while (pos > 0 && pos < document.getLength()) {
        c = document.getChar(pos);
        if (Character.isWhitespace(c) && !Character.isLetter(c)) break;
        --pos;
      }
      start = pos;
      pos = offset;
      int length = document.getLength();

      while (pos < length - 1) {
        c = document.getChar(pos);
        if (!Character.isJavaIdentifierPart(c)) break;
        ++pos;
      }
      end = pos;

    } catch (BadLocationException x) {
    }

    if (start >= -1 && end > -1) {
      return new Region(start, end - start);
    }

    return null;
  }
  /*
   * @see org.eclipse.jdt.internal.ui.text.java.LazyJavaCompletionProposal#apply(org.eclipse.jface.text.IDocument, char, int)
   */
  @Override
  public void apply(IDocument document, char trigger, int offset) {
    try {
      boolean insertClosingParenthesis = trigger == '(' && autocloseBrackets();
      if (insertClosingParenthesis) {
        StringBuffer replacement = new StringBuffer(getReplacementString());
        updateReplacementWithParentheses(replacement);
        setReplacementString(replacement.toString());
        trigger = '\0';
      }

      super.apply(document, trigger, offset);

      if (fImportRewrite != null && fImportRewrite.hasRecordedChanges()) {
        int oldLen = document.getLength();
        fImportRewrite
            .rewriteImports(new NullProgressMonitor())
            .apply(document, TextEdit.UPDATE_REGIONS);
        setReplacementOffset(getReplacementOffset() + document.getLength() - oldLen);
      }

      if (insertClosingParenthesis) setUpLinkedMode(document, ')');

      rememberSelection();
    } catch (CoreException e) {
      JavaPlugin.log(e);
    } catch (BadLocationException e) {
      JavaPlugin.log(e);
    }
  }
Ejemplo n.º 3
0
  /**
   * @return the current token and its initial offset for this token
   * @param the chars to be considered separators (note that whitespace chars are always considered
   *     separators and don't need to be in this set).
   * @throws BadLocationException
   */
  public Tuple<String, Integer> getCurrToken(Set<Character> separatorChars)
      throws BadLocationException {
    int offset = getAbsoluteCursorOffset();
    int i = offset;

    if (i > doc.getLength()) {
      return new Tuple<String, Integer>("", doc.getLength()); // $NON-NLS-1$
    }

    while (i > 0) {
      char ch = doc.getChar(i - 1);
      if (separatorChars.contains(ch) || Character.isWhitespace(ch)) {
        break;
      }
      i--;
    }

    Tuple<String, Integer> tup = new Tuple<String, Integer>(doc.get(i, offset - i), offset);

    String prefix = tup.o1;

    // ok, now, get the rest of the token, as we already have its prefix
    int start = tup.o2 - prefix.length();
    int end = start;
    while (doc.getLength() - 1 >= end) {
      char ch = doc.getChar(end);
      if (separatorChars.contains(ch) || Character.isWhitespace(ch)) {
        break;
      }
      end++;
    }
    String post = doc.get(tup.o2, end - tup.o2);
    return new Tuple<String, Integer>(prefix + post, start);
  }
Ejemplo n.º 4
0
  /**
   * This function gets the activation token from the document given the current cursor position.
   *
   * @param document this is the document we want info on
   * @param offset this is the cursor position
   * @param getFullQualifier if true we get the full qualifier (even if it passes the current cursor
   *     location)
   * @return a tuple with the activation token and the cursor offset (may change if we need to get
   *     the full qualifier, otherwise, it is the same offset passed as a parameter).
   */
  public static Tuple<String, Integer> extractActivationToken(
      IDocument document, int offset, boolean getFullQualifier) {
    try {
      if (getFullQualifier) {
        // if we have to get the full qualifier, we'll have to walk the offset (cursor) forward
        while (offset < document.getLength()) {
          char ch = document.getChar(offset);
          if (Character.isJavaIdentifierPart(ch)) {
            offset++;
          } else {
            break;
          }
        }
      }
      int i = offset;

      if (i > document.getLength()) {
        return new Tuple<String, Integer>("", document.getLength()); // $NON-NLS-1$
      }

      while (i > 0) {
        char ch = document.getChar(i - 1);
        if (!Character.isJavaIdentifierPart(ch)) {
          break;
        }
        i--;
      }

      return new Tuple<String, Integer>(document.get(i, offset - i), offset);
    } catch (BadLocationException e) {
      return new Tuple<String, Integer>("", offset); // $NON-NLS-1$
    }
  }
  /** This method should be called after all the lines received were processed. */
  private void onAfterAllLinesHandled(
      final String finalText,
      final boolean finalAddedParen,
      final int finalStart,
      final int finalOffset,
      final boolean finalAddedCloseParen,
      final String finalIndentString,
      final int finalNewDeltaCaretPosition) {
    boolean shiftsCaret = true;
    String newText = finalText.substring(finalStart, finalText.length());
    if (finalAddedParen) {
      String cmdLine = getCommandLine();
      Document parenDoc = new Document(cmdLine + newText);
      int currentOffset = cmdLine.length() + 1;
      DocCmd docCmd = new DocCmd(currentOffset, 0, "(");
      docCmd.shiftsCaret = true;
      try {
        strategy.customizeParenthesis(parenDoc, docCmd);
      } catch (BadLocationException e) {
        Log.log(e);
      }
      newText = docCmd.text + newText.substring(1);
      if (!docCmd.shiftsCaret) {
        shiftsCaret = false;
        setCaretOffset(finalOffset + (docCmd.caretOffset - currentOffset));
      }
    } else if (finalAddedCloseParen) {
      String cmdLine = getCommandLine();
      String existingDoc = cmdLine + finalText.substring(1);
      int cmdLineOffset = cmdLine.length();
      if (existingDoc.length() > cmdLineOffset) {
        Document parenDoc = new Document(existingDoc);
        DocCmd docCmd = new DocCmd(cmdLineOffset, 0, ")");
        docCmd.shiftsCaret = true;
        boolean canSkipOpenParenthesis;
        try {
          canSkipOpenParenthesis = strategy.canSkipCloseParenthesis(parenDoc, docCmd);
        } catch (BadLocationException e) {
          canSkipOpenParenthesis = false;
          Log.log(e);
        }
        if (canSkipOpenParenthesis) {
          shiftsCaret = false;
          setCaretOffset(finalOffset + 1);
          newText = newText.substring(1);
        }
      }
    }

    // and now add the last line (without actually handling it).
    String cmd = finalIndentString + newText;
    cmd = convertTabs(cmd);
    applyStyleToUserAddedText(cmd, doc.getLength());
    appendText(cmd);
    if (shiftsCaret) {
      setCaretOffset(doc.getLength() - finalNewDeltaCaretPosition);
    }

    history.update(getCommandLine());
  }
  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
    }
  }
  protected void endProcessing() {
    super.endProcessing();
    ValidatorStrategy validatorStrategy = getValidatorStrategy();
    if (validatorStrategy != null) {
      validatorStrategy.endProcessing();
    }
    /* single spell-check for everything to ensure that SpellingProblem offsets are correct */
    IReconcilingStrategy spellingStrategy = getSpellcheckStrategy();
    IDocument document = getDocument();
    if (spellingStrategy != null && document != null) {
      spellingStrategy.reconcile(new Region(0, document.getLength()));
    }

    IReconcilingStrategy semanticHighlightingStrategy = getSemanticHighlightingStrategy();
    if (semanticHighlightingStrategy != null && document != null) {
      semanticHighlightingStrategy.reconcile(new Region(0, document.getLength()));
    }

    if ((getTextViewer() instanceof ISourceViewer)) {
      ISourceViewer sourceViewer = (ISourceViewer) getTextViewer();
      IAnnotationModel annotationModel = sourceViewer.getAnnotationModel();
      for (int i = 0; i < fReconcileListeners.length; i++) {
        fReconcileListeners[i].reconciled(
            document, annotationModel, false, new NullProgressMonitor());
      }
    }
  }
Ejemplo n.º 8
0
  private void smartIndentAfterClosingBracket(IDocument d, DocumentCommand c) {
    if (c.offset == -1 || d.getLength() == 0) return;

    try {
      int p = (c.offset == d.getLength() ? c.offset - 1 : c.offset);
      int line = d.getLineOfOffset(p);
      int start = d.getLineOffset(line);
      int whiteend = findEndOfWhiteSpace(d, start, c.offset);

      JavaHeuristicScanner scanner = new JavaHeuristicScanner(d);
      JavaIndenter indenter = new JavaIndenter(d, scanner, fProject);

      // shift only when line does not contain any text up to the closing bracket
      if (whiteend == c.offset) {
        // evaluate the line with the opening bracket that matches out closing bracket
        int reference = indenter.findReferencePosition(c.offset, false, true, false, false);
        int indLine = d.getLineOfOffset(reference);
        if (indLine != -1 && indLine != line) {
          // take the indent of the found line
          StringBuffer replaceText = new StringBuffer(getIndentOfLine(d, indLine));
          // add the rest of the current line including the just added close bracket
          replaceText.append(d.get(whiteend, c.offset - whiteend));
          replaceText.append(c.text);
          // modify document command
          c.length += c.offset - start;
          c.offset = start;
          c.text = replaceText.toString();
        }
      }
    } catch (BadLocationException e) {
      JavaPlugin.log(e);
    }
  }
  protected void setEntireDocumentDirty(IDocument document) {
    super.setEntireDocumentDirty(document);

    // make the entire document dirty
    // this also happens on a "save as"
    if (document != null && isInstalled() && fLastPartitions != null && document.getLength() == 0) {
      /**
       * https://bugs.eclipse.org/bugs/show_bug.cgi?id=199053
       *
       * <p>Process the strategies for the last known-good partitions.
       */
      for (int i = 0; i < fLastPartitions.length; i++) {
        ValidatorStrategy validatorStrategy = getValidatorStrategy();
        if (validatorStrategy != null) {
          validatorStrategy.reconcile(
              fLastPartitions[i], createDirtyRegion(fLastPartitions[i], DirtyRegion.REMOVE));
        }
      }
      IReconcilingStrategy spellingStrategy = getSpellcheckStrategy();
      if (spellingStrategy != null) {
        spellingStrategy.reconcile(new Region(0, document.getLength()));
      }

      // if there is a folding strategy then reconcile it
      if (getFoldingStrategy() != null) {
        getFoldingStrategy().reconcile(new Region(0, document.getLength()));
      }
    }
  }
  /**
   * Provide the initialization of the listeners additions. The Window, Part, and Document Listener
   * are added. Note that sensor shell should be instantiated before this method is called because
   * <code>processActivity()</code> method uses sensor shell instance.
   */
  private void registerListeners() {
    IWorkbench workbench = EclipseSensorPlugin.getInstance().getWorkbench();

    // :RESOLVED: JULY 1, 2003
    // Supports the multiple window for sensor collection.
    IWorkbenchWindow[] activeWindows = workbench.getWorkbenchWindows();

    // Check if window listener is not added yet. Otherwise multi instances are notified.
    if (this.windowListener == null) {
      this.windowListener = new WindowListenerAdapter();
      workbench.addWindowListener(new WindowListenerAdapter());
    }

    for (int i = 0; i < activeWindows.length; i++) {
      IWorkbenchPage activePage = activeWindows[i].getActivePage();
      activePage.addPartListener(new PartListenerAdapter());
      IEditorPart activeEditorPart = activePage.getActiveEditor();

      // Adds this EclipseSensorPlugin instance to IDocumentListener
      // only when activeEditorPart is the instance of ITextEditor
      // so that null case is also ignored.
      if (activeEditorPart instanceof ITextEditor) {
        // Sets activeTextEditor. Otherwise a first activated file would not be recorded.
        this.activeTextEditor = (ITextEditor) activeEditorPart;
        // Gets opened file since the initial opened file is not notified from IPartListener.
        URI fileResource = EclipseSensor.this.getFileResource(this.activeTextEditor);

        Map<String, String> keyValueMap = new HashMap<String, String>();
        keyValueMap.put(EclipseSensorConstants.SUBTYPE, "Open");
        keyValueMap.put(EclipseSensorConstants.UNIT_TYPE, EclipseSensorConstants.FILE);
        keyValueMap.put(
            EclipseSensorConstants.UNIT_NAME, EclipseSensor.this.extractFileName(fileResource));
        this.addDevEvent(
            EclipseSensorConstants.DEVEVENT_EDIT,
            fileResource,
            keyValueMap,
            "Opened " + fileResource.toString());

        IDocumentProvider provider = this.activeTextEditor.getDocumentProvider();
        IDocument document = provider.getDocument(activeEditorPart.getEditorInput());

        // Initially sets active buffer and threshold buffer.
        // Otherwise a first activated buffer would not be recorded.
        this.activeBufferSize = document.getLength();
        this.thresholdBufferSize = document.getLength();
        document.addDocumentListener(new DocumentListenerAdapter());
      }
    }

    // Handles breakpoint set/unset event.
    IBreakpointManager bpManager = DebugPlugin.getDefault().getBreakpointManager();
    bpManager.addBreakpointListener(new BreakPointerSensor(this));

    // Listens to debug event.
    DebugPlugin.getDefault().addDebugEventListener(new DebugSensor(this));

    // Creates instance to handle build error.
    this.buildErrorSensor = new BuildErrorSensor(this);
  }
 public ParamRegion findEnclosingPeerCharacters(IDocument document, int offset, int length) {
   if (document == null || offset < 0 || offset > document.getLength()) return null;
   try {
     DocumentAccessor doc = new DocumentAccessor(document);
     return findEnclosingPeers(document, doc, offset, length, 0, document.getLength());
   } catch (BadLocationException ble) {
     return null;
   }
 }
 protected String getSurroundingText(IDocument document, int offset, int context) {
   int start = (offset - context < 0) ? 0 : offset - context;
   int end =
       (offset + context > document.getLength() - 1) ? document.getLength() - 1 : offset + context;
   try {
     return document.get(start, offset - start) + "|" + document.get(offset, end - (offset + 1));
   } catch (BadLocationException e) {
     return StringUtil.EMPTY;
   }
 }
Ejemplo n.º 13
0
 @Override
 public void documentChanged(DocumentEvent event) {
   IDocument newDoc = event.getDocument();
   if (docLines != newDoc.getNumberOfLines()) {
     updateAnnotations(false);
     docLines = newDoc.getNumberOfLines();
     docLength = newDoc.getLength();
   } else {
     changeAnnotations(event.getOffset(), newDoc.getLength());
   }
 }
 /** Shows the prompt for the user (e.g.: >>>) */
 protected void appendInvitation(boolean async) {
   int start = doc.getLength();
   String promptStr = prompt.toString();
   IConsoleStyleProvider styleProvider = viewer.getStyleProvider();
   if (styleProvider != null) {
     ScriptStyleRange style = styleProvider.createPromptStyle(promptStr, start);
     if (style != null) {
       addToPartitioner(style);
     }
   }
   appendText(promptStr); // caret already updated
   setCaretOffset(doc.getLength(), async);
   revealEndOfDocument();
 }
Ejemplo n.º 15
0
 public void testLiterateSequences() throws CoreException {
   IDocument document = createDocument("A\\begin{code}B\\end{code}C\n");
   // scanner should not know about literate stuff
   ITokenScanner scanner = new HaskellCodeScanner(false);
   scanner.setRange(document, 0, document.getLength());
   assertColor(scanner.nextToken(), ColorProvider.DEFAULT_OTHER);
   // scanner should recognize literate sequences as comments
   scanner = new HaskellCodeScanner(true);
   scanner.setRange(document, 0, document.getLength());
   assertColor(scanner.nextToken(), ColorProvider.DEFAULT_OTHER);
   assertColor(scanner.nextToken(), ColorProvider.DEFAULT_COMMENT);
   assertColor(scanner.nextToken(), ColorProvider.DEFAULT_OTHER);
   assertColor(scanner.nextToken(), ColorProvider.DEFAULT_COMMENT);
   assertColor(scanner.nextToken(), ColorProvider.DEFAULT_OTHER);
 }
  /**
   * Indents a line with a given indentation level.
   *
   * @param document the document being processed.
   * @param lineStart the offset at which the target line starts
   * @param indentationLevel the indentation level to use
   * @exception BadLocationException if the offset is invalid in this document
   */
  private void setIndentLevel(
      final IDocument document, final int lineStart, final int indentationLevel)
      throws BadLocationException {
    int lastWhiteSpace = lineStart;
    char c;
    while (lastWhiteSpace < document.getLength()) {
      c = document.getChar(lastWhiteSpace);
      if (c == ' ' || c == '\t') {
        lastWhiteSpace++;
      } else {
        break;
      }
    }

    for (int i = indentArray.size() - 1; i < indentationLevel; i++) {
      indentArray.add(indentArray.get(i) + IndentationSupport.getIndentString());
    }

    if (!document
        .get(lineStart, lastWhiteSpace - lineStart)
        .equals(indentArray.get(indentationLevel))) {
      multiEdit.addChild(
          new ReplaceEdit(
              lineStart, lastWhiteSpace - lineStart, indentArray.get(indentationLevel)));
    }
  }
Ejemplo n.º 17
0
  @Override
  public boolean performFinish() {
    IFile resultFile = page.getResultFile();
    if (resultFile != null) {
      ABSEditor editor =
          UtilityFunctions.openABSEditorForFile(resultFile.getLocation(), resultFile.getProject());
      IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput());

      // modules are always added the the end of the document
      final int off = document.getLength();

      try {
        document.replace(off, 0, insertType.getInsertionString(page.getResult()));
        final int insertOffset = insertType.getInsertOffset(page.getResult());

        WizardUtil.saveEditorAndGotoOffset(editor, insertOffset);

        return true;
      } catch (BadLocationException e) {
        MessageDialog.openError(
            getShell(),
            "Error",
            "Fatal error: The insertion position for the new module does not longer exist. Please save the target file and try again.");
        e.printStackTrace();
        return false;
      }
    } else {
      MessageDialog.openError(
          getShell(),
          "Error",
          "Fatal error: No file reference was passed by the wizard. Please try again to use the wizard and select a valid file.");
      return false;
    }
  }
  /** 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 ITypedRegion getPartition(IDocument doc, int offset) throws BadLocationException {
   ITypedRegion part =
       TextUtilities.getPartition(
           doc, IPropertiesFilePartitions.PROPERTIES_FILE_PARTITIONING, offset, true);
   if (part.getType() == IDocument.DEFAULT_CONTENT_TYPE
       && part.getLength() == 0
       && offset == doc.getLength()
       && offset > 0) {
     // A special case because when cursor at end of document and just after a '=' sign, then we
     // get a DEFAULT content type
     // with a empty region. We rather would get the non-empty 'Value' partition just before that
     // (which has the assignment in it.
     char assign = doc.getChar(offset - 1);
     if (isAssign(assign)) {
       return new TypedRegion(offset - 1, 1, IPropertiesFilePartitions.PROPERTY_VALUE);
     } else {
       // For a similar case but where there's extra spaces after the '='
       ITypedRegion previousPart =
           TextUtilities.getPartition(
               doc, IPropertiesFilePartitions.PROPERTIES_FILE_PARTITIONING, offset - 1, true);
       int previousEnd = previousPart.getOffset() + previousPart.getLength();
       if (previousEnd == offset) {
         // prefer this over a 0 length partition ending at the same location
         return previousPart;
       }
     }
   }
   return part;
 }
Ejemplo n.º 20
0
 private int findChangeLogPattern(IDocument changelog_doc, int startOffset) {
   // find the "pattern" of a changelog entry. Not a specific one,
   // but one that "looks" like an entry
   int nextEntry = startOffset;
   int line_length = 0;
   String entry = ""; // $NON-NLS-1$
   while (nextEntry < changelog_doc.getLength()) {
     try {
       // Get the line of interest in the changelog document
       line_length = changelog_doc.getLineOfOffset(nextEntry);
       entry = changelog_doc.get(nextEntry, changelog_doc.getLineLength(line_length));
       // Attempt to find date pattern on line
       if (matchDatePattern(entry)) {
         // nextDate -= entry.length()+1;
         break;
       }
       // If no date matches, move to the next line
       nextEntry += changelog_doc.getLineLength(line_length);
     } catch (BadLocationException e) {
       ChangelogPlugin.getDefault()
           .getLog()
           .log(
               new Status(
                   IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e.getMessage(), e));
     }
   }
   return nextEntry;
 }
Ejemplo n.º 21
0
 /*
  * @see org.eclipse.cdt.core.dom.ast.ASTVisitor#leave(org.eclipse.cdt.core.dom.ast.IASTTranslationUnit)
  */
 @Override
 public int leave(IASTTranslationUnit tu) {
   super.leave(tu);
   assert getCurrentContainer().getTypeCode() == ICElement.C_UNIT;
   pop(fDocument.getLength());
   return PROCESS_SKIP;
 }
  /**
   * If you found an opening peer, you'll want to look for a closing peer.
   *
   * @param offset
   * @param openingPeer
   * @param closingPeer
   * @param document
   * @return the offset of the closing peer
   * @throws IOException
   */
  public int searchForClosingPeer(
      int offset, char openingPeer, char closingPeer, IDocument document) {
    try {
      fReader.configureForwardReader(document, offset + 1, document.getLength(), true, true, true);

      int stack = 1;
      int c = fReader.read();
      while (c != PythonCodeReader.EOF) {
        if (c == openingPeer && c != closingPeer) stack++;
        else if (c == closingPeer) stack--;

        if (stack
            <= 0) { // <= 0 because if we have a closing peer without an opening one, we'll return
                    // it.
          return fReader.getOffset();
        }

        c = fReader.read();
      }

      return -1;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  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;
  }
Ejemplo n.º 24
0
  /**
   * Checks whether the content of <code>document</code> in the range (<code>offset</code>, <code>
   * length</code>) contains the <code>new</code> keyword.
   *
   * @param document the document being modified
   * @param offset the first character position in <code>document</code> to be considered
   * @param length the length of the character range to be considered
   * @param partitioning the document partitioning
   * @return <code>true</code> if the specified character range contains a <code>new</code> keyword,
   *     <code>false</code> otherwise.
   */
  private static boolean isNewMatch(
      IDocument document, int offset, int length, String partitioning) {
    Assert.isTrue(length >= 0);
    Assert.isTrue(offset >= 0);
    Assert.isTrue(offset + length < document.getLength() + 1);

    try {
      String text = document.get(offset, length);
      int pos = text.indexOf("new"); // $NON-NLS-1$

      while (pos != -1 && !isDefaultPartition(document, pos + offset, partitioning))
        pos = text.indexOf("new", pos + 2); // $NON-NLS-1$

      if (pos < 0) return false;

      if (pos != 0 && Character.isJavaIdentifierPart(text.charAt(pos - 1))) return false;

      if (pos + 3 < length && Character.isJavaIdentifierPart(text.charAt(pos + 3))) return false;

      return true;

    } catch (BadLocationException e) {
    }
    return false;
  }
 private final void processNode(SemanticToken token, DartNode node) {
   token.update(node);
   token.attachSource(fSourceViewer.getDocument());
   // sometimes node has wrong source range; log problem
   if (token.getSource() == null) {
     IDocument document = fSourceViewer.getDocument();
     if (node != null && document != null) {
       SourceInfo sourceInfo = node.getSourceInfo();
       if (sourceInfo != null) {
         DartToolsPlugin.log(
             "Bad node: "
                 + node.getClass().getName()
                 + " offset:"
                 + sourceInfo.getOffset()
                 + " len:"
                 + sourceInfo.getLength()
                 + " in document: "
                 + document.getLength());
       }
     }
     return;
   }
   // try SemanticHighlighting instances
   for (int i = 0, n = fJobSemanticHighlightings.length; i < n; i++) {
     if (fJobHighlightings[i].isEnabled()) {
       SemanticHighlighting semanticHighlighting = fJobSemanticHighlightings[i];
       // try multiple positions
       {
         List<SourceRange> ranges = semanticHighlighting.consumesMulti(token);
         if (ranges != null) {
           for (SourceRange range : ranges) {
             int offset = range.getOffset();
             int length = range.getLength();
             if (offset > -1 && length > 0) {
               fCollector.addPosition(offset, length, fJobHighlightings[i]);
             }
           }
           break;
         }
       }
       // try single position
       boolean consumes;
       if (node instanceof DartIdentifier) {
         consumes = semanticHighlighting.consumesIdentifier(token);
       } else {
         consumes = semanticHighlighting.consumes(token);
       }
       if (consumes) {
         int offset = node.getSourceInfo().getOffset();
         int length = node.getSourceInfo().getLength();
         if (offset > -1 && length > 0) {
           fCollector.addPosition(offset, length, fJobHighlightings[i]);
         }
         break;
       }
     }
   }
   token.clear();
 }
  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.
    }
  }
 private static boolean isBeforeCloseBrace(IDocument document, int offset, int endLineOffset)
     throws BadLocationException {
   int nonEmptyOffset = findEndOfWhiteSpaceAfter(document, offset, endLineOffset);
   if (nonEmptyOffset == document.getLength()) {
     nonEmptyOffset--;
   }
   return document.getChar(nonEmptyOffset) == CLOSING_BRACE_CHAR;
 }
 /**
  * Appends some text at the end of the document.
  *
  * @param text the text to be added.
  */
 protected void appendText(String text) {
   int initialOffset = doc.getLength();
   try {
     doc.replace(initialOffset, 0, text);
   } catch (BadLocationException e) {
     Log.log(e);
   }
 }
Ejemplo n.º 29
0
 /**
  * Creates a JavaNode for a CU. It represents the root of a JavaNode tree, so its parent is null.
  *
  * @param document the document which contains the Java element
  */
 public JavaNode(IDocument document) {
   super(
       CU,
       JavaCompareUtilities.buildID(CU, "root"),
       document,
       0,
       document.getLength()); // $NON-NLS-1$
 }
  public boolean openHyperLink() {
    String localiz = getLocalization();
    if (localiz == null) {
      return false;
    } else if (fBase.getUnderlyingResource() == null) {
      return false;
    } else if (fElement.length() == 0 || fElement.charAt(0) != '%') {
      return false;
    }

    IProject proj = fBase.getUnderlyingResource().getProject();
    IFile file = proj.getFile(localiz + ".properties"); // $NON-NLS-1$
    if (!file.exists()) return false;

    try {
      IEditorPart editor = IDE.openEditor(PDEPlugin.getActivePage(), file);
      if (!(editor instanceof TextEditor)) return false;
      TextEditor tEditor = (TextEditor) editor;
      IDocument doc = tEditor.getDocumentProvider().getDocument(tEditor.getEditorInput());
      if (doc == null) return false;

      try {
        String key = fElement.substring(1);
        int keyLen = key.length();
        int length = doc.getLength();
        int start = 0;
        IRegion region = null;
        FindReplaceDocumentAdapter docSearch = new FindReplaceDocumentAdapter(doc);
        while ((region = docSearch.find(start, key, true, false, false, false)) != null) {
          int offset = region.getOffset();
          if (offset > 0) {
            // check for newline before
            char c = doc.getChar(offset - 1);
            if (c != '\n' && c != '\r') {
              start += keyLen;
              continue;
            }
          }
          if (offset + keyLen < length) {
            // check for whitespace / assign symbol after
            char c = doc.getChar(offset + keyLen);
            if (!Character.isWhitespace(c) && c != '=' && c != ':') {
              start += keyLen;
              continue;
            }
          }
          tEditor.selectAndReveal(offset, keyLen);
          break;
        }
      } catch (BadLocationException e) {
        PDEPlugin.log(e);
      }

    } catch (PartInitException e) {
      return false;
    }
    return true;
  }