예제 #1
0
  /**
   * Adds a line to the document.
   *
   * @param doc the document
   * @param endLineDelim the delimiter that should be used
   * @param contents what should be added (the end line delimiter may be added before or after those
   *     contents (depending on what are the current contents of the document).
   * @param afterLine the contents should be added after the line specified here.
   */
  public static void addLine(IDocument doc, String endLineDelim, String contents, int afterLine) {
    try {

      int offset = -1;
      if (doc.getNumberOfLines() > afterLine) {
        offset = doc.getLineInformation(afterLine + 1).getOffset();

      } else {
        offset = doc.getLineInformation(afterLine).getOffset();
      }

      if (doc.getNumberOfLines() - 1 == afterLine) {
        contents = endLineDelim + contents;
      }

      if (!contents.endsWith(endLineDelim)) {
        contents += endLineDelim;
      }

      if (offset >= 0) {
        doc.replace(offset, 0, contents);
      }
    } catch (BadLocationException e) {
      Log.log(e);
    }
  }
 @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());
   }
 }
예제 #3
0
 public Parser(IDocument document, IResource resource) {
   this.document = document;
   this.resource = resource;
   this.numberOfLines = document.getNumberOfLines();
   this.configuration = ConfigurationParser.getConfiguration(document);
   this.componentNames = configuration.componentNames;
 }
예제 #4
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();
  }
예제 #5
0
  /** Creates Annotations for FOP */
  private void createFOPAnnotations() throws BadLocationException {
    AnnotationModelEvent event = new AnnotationModelEvent(this);
    FSTModel model = project.getFSTModel();

    if (model == null) {
      composer.buildFSTModel();
      model = project.getFSTModel();
    }
    if (model == null) {
      return;
    }

    clear();

    if (file.getParent() instanceof IFolder) {
      if (isInBuildFolder((IFolder) file.getParent())) {
        /* annotations for generated files */
        FSTClass clazz = model.getClass(model.getAbsoluteClassName(file));
        if (clazz == null) {
          return;
        }
        if (!clazz.hasComposedLines) {
          clazz.hasComposedLines = true;
          composer.postCompile(null, file);
        }
        for (FSTFeature fstFeature : model.getFeatures()) {
          FSTRole role = clazz.getRole(fstFeature.getName());
          if (role == null) {
            continue;
          }
          for (FSTMethod m : role.getAllMethods()) {
            createFOPComposedAnnotations(event, fstFeature, m);
          }
          for (FSTField f : role.getAllFields()) {
            createFOPComposedAnnotations(event, fstFeature, f);
          }
        }
      } else {
        /* annotations for source files */
        String featureName = getFeature((IFolder) file.getParent());
        if (featureName != null) {
          FSTFeature fstFeature = model.getFeature(featureName);
          if (fstFeature != null) {
            // bar at the left of the editor
            final int color = fstFeature.getColor();
            for (int line = 0; line < document.getNumberOfLines(); line++) {
              Position position = new Position(document.getLineOffset(line), 1);
              ColorAnnotation cafh =
                  new ColorAnnotation(color, position, ColorAnnotation.TYPE_IMAGE);
              cafh.setText(fstFeature.getName());
              annotations.add(cafh);
              event.annotationAdded(cafh);
            }
          }
        }
      }
    }
  }
예제 #6
0
 private void gotoLineEnd() throws BadLocationException {
   int line = fDocument.getLineOfOffset(fOffset);
   int lines = fDocument.getNumberOfLines();
   if (line + 1 == lines) {
     fOffset = fDocument.getLength() - 1;
   } else {
     fOffset = fDocument.getLineOffset(line + 1);
   }
 }
 /**
  * Corrects the {@link IMarker#CHAR_START} and {@link IMarker#CHAR_END} values as needed
  *
  * @param document
  * @param marker
  * @param line
  * @throws BadLocationException
  */
 void ensureRanges(IDocument document, IMarker marker, int line) throws BadLocationException {
   if (line < 0 || line > document.getNumberOfLines()) {
     return;
   }
   IRegion region = document.getLineInformation(line - 1);
   int charstart = region.getOffset();
   int charend = charstart + region.getLength();
   MarkerUtilities.setCharStart(marker, charstart);
   MarkerUtilities.setCharEnd(marker, charend);
 }
  /** Retrieves the FSTDirectives from the changed document. */
  private LinkedList<FSTDirective> getNewDirectives() {
    Vector<String> lines = new Vector<String>();

    for (int i = 0; i < document.getNumberOfLines(); i++) {
      try {
        lines.add(document.get(document.getLineOffset(i), document.getLineLength(i)));
      } catch (BadLocationException e) {
        UIPlugin.getDefault().logError(e);
      }
    }

    return composer.buildModelDirectivesForFile(lines);
  }
 private int getNextLineOffset(final IDocument doc, final int endLine) {
   try {
     if (endLine >= 0 && endLine + 1 < doc.getNumberOfLines()) {
       return doc.getLineOffset(endLine + 1);
     } else {
       return -1;
     }
   } catch (final BadLocationException e) {
     // don't show an error
     RUIPlugin.logError(RUIPlugin.INTERNAL_ERROR, "Error while find next line.", e); // $NON-NLS-1$
     return -1;
   }
 }
예제 #10
0
  /** Retrieves the FSTDirectives from the changed document. */
  private LinkedList<FSTDirective> getNewDirectives() {
    Vector<String> lines = new Vector<String>();

    for (int i = 0; i < document.getNumberOfLines(); i++) {
      try {
        lines.add(document.get(document.getLineOffset(i), document.getLineLength(i)));
      } catch (BadLocationException e) {
        LogService.getInstance().log(LogLevel.DEBUG, e.getMessage());
      }
    }

    return composer.buildModelDirectivesForFile(lines);
  }
예제 #11
0
 /**
  * @param offset the offset we want to get the line
  * @return the line of the passed offset
  */
 public static int getLineOfOffset(IDocument doc, int offset) {
   try {
     return doc.getLineOfOffset(offset);
   } catch (BadLocationException e) {
     if (offset > doc.getLength() - 1) {
       int numberOfLines = doc.getNumberOfLines();
       if (numberOfLines == 0) {
         return 0;
       }
       return numberOfLines - 1;
     }
     return 0;
   }
 }
예제 #12
0
  /** In event of partial selection, used to select the full lines involved. */
  public void selectCompleteLine() {
    if (doc.getNumberOfLines() == 1) {
      this.textSelection = new TextSelection(doc, 0, doc.getLength());
      return;
    }
    IRegion endLine = getEndLine();
    IRegion startLine = getStartLine();

    this.textSelection =
        new TextSelection(
            doc,
            startLine.getOffset(),
            endLine.getOffset() + endLine.getLength() - startLine.getOffset());
  }
예제 #13
0
  /**
   * Updates all the cached information about the lines to be painted and to be cleared. Returns
   * <code>true</code> if the line number of the cursor line has changed.
   *
   * @return <code>true</code> if cursor line changed
   */
  private boolean updateHighlightLine() {
    try {

      IDocument document = fViewer.getDocument();
      int modelCaret = getModelCaret();
      int lineNumber = document.getLineOfOffset(modelCaret);
      Point selection = fViewer.getTextWidget().getSelectionRange();

      // redraw if the current line number is different from the last line number we painted
      // initially fLastLineNumber is -1
      if (lineNumber != fLastLineNumber
          || !overlaps(fCurrentLine, modelCaret)
          || (selection.y != 0)) {
        // Handle non-empty selections (turn off highlight line)
        if (selection.y != 0 && fLastLine.equals(fCurrentLine)) {
          if (fLastSelection.equals(selection)) // selection didn't change
          {
            return false; // don't redraw the highlight line
          }
          fLastSelection = selection;
          return true; // selection changed
        }
        fLastSelection = selection;
        // Update the current and last lines
        fLastLine.offset = fCurrentLine.offset;
        fLastLine.length = fCurrentLine.length;
        fLastLine.isDeleted = fCurrentLine.isDeleted;

        if (fCurrentLine.isDeleted) {
          fCurrentLine.isDeleted = false;
          fPositionManager.managePosition(fCurrentLine);
        }

        fCurrentLine.offset = document.getLineOffset(lineNumber);
        if (lineNumber == document.getNumberOfLines() - 1) {
          fCurrentLine.length = document.getLength() - fCurrentLine.offset;
        } else {
          fCurrentLine.length = document.getLineOffset(lineNumber + 1) - fCurrentLine.offset;
        }

        fLastLineNumber = lineNumber;
        return true;
      }
    } catch (BadLocationException e) {
    }

    return false;
  }
  /**
   * Adds some text that came as an output to stdout or stderr to the console.
   *
   * @param out the text that should be added
   * @param stdout true if it came from stdout and also if it came from stderr
   */
  private void addToConsoleView(String out, boolean stdout) {
    if (out.length() == 0) {
      return; // nothing to add!
    }
    int start = doc.getLength();

    IConsoleStyleProvider styleProvider = viewer.getStyleProvider();
    Tuple<List<ScriptStyleRange>, String> style = null;
    if (styleProvider != null) {
      if (stdout) {
        style = styleProvider.createInterpreterOutputStyle(out, start);
      } else { // stderr
        style = styleProvider.createInterpreterErrorStyle(out, start);
      }
      if (style != null) {
        for (ScriptStyleRange s : style.o1) {
          addToPartitioner(s);
        }
      }
    }
    if (style != null) {
      appendText(style.o2);
    }

    TextSelectionUtils ps = new TextSelectionUtils(doc, start);
    int cursorLine = ps.getCursorLine();
    int numberOfLines = doc.getNumberOfLines();

    // right after appending the text, let's notify line trackers
    for (int i = cursorLine; i < numberOfLines; i++) {
      try {
        int offset = ps.getLineOffset(i);
        int endOffset = ps.getEndLineOffset(i);

        Region region = new Region(offset, endOffset - offset);

        for (IConsoleLineTracker lineTracker : this.consoleLineTrackers) {
          lineTracker.lineAppended(region);
        }
      } catch (Exception e) {
        Log.log(e);
      }
    }
  }
 /*
  * (non-Javadoc)
  *
  * @see org.eclipse.jface.action.IAction#run()
  */
 public void run() {
   try {
     /*
      * Test if there are any markers at the current position.
      * if there are any, remove breakpointmarker, otherwise create a
      * new one.
      */
     List list = getMarkers();
     if (list.isEmpty()) {
       // create new markers
       IDocument document = getDocument();
       int lineNumber = getVerticalRulerInfo().getLineOfLastMouseButtonActivity();
       if (lineNumber >= document.getNumberOfLines()) {
         return;
       }
       try {
         IRegion line = document.getLineInformation(lineNumber);
         ITextSelection selection =
             new TextSelection(document, line.getOffset(), line.getLength());
         // fBreakpointAdapter.toggleLineBreakpoints(fTextEditor, selection);
         fBreakpointAdapter.toggleBreakpoints(fTextEditor, selection);
       } catch (BadLocationException e) {
         // likely document is folded so you cannot get the line information of the folded line
       }
     } else {
       // remove existing breakpoints of any type
       IBreakpointManager manager = DebugPlugin.getDefault().getBreakpointManager();
       Iterator iterator = list.iterator();
       while (iterator.hasNext()) {
         IMarker marker = (IMarker) iterator.next();
         IBreakpoint breakpoint = manager.getBreakpoint(marker);
         if (breakpoint != null) {
           breakpoint.delete();
         }
       }
     }
   } catch (CoreException e) {
     // JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.adding.message1"), e); //$NON-NLS-1$
     // JDIDebugUIPlugin.errorDialog(ActionMessages.ManageBreakpointRulerAction_error_adding_message1, e);
     // This message may not make sense FIXME
     JDIDebugUIPlugin.errorDialog(
         ActionMessages.ManageMethodBreakpointActionDelegate_methodNonAvailable, e);
   }
 }
  /*
   * @see org.eclipse.core.internal.filebuffers.textmanipulation.TextFileBufferOperation#computeTextEdit(org.eclipse.core.filebuffers.ITextFileBuffer, org.eclipse.core.runtime.IProgressMonitor)
   */
  protected MultiTextEditWithProgress computeTextEdit(
      ITextFileBuffer fileBuffer, IProgressMonitor progressMonitor) throws CoreException {
    IDocument document = fileBuffer.getDocument();
    int lineCount = document.getNumberOfLines();

    progressMonitor = Progress.getMonitor(progressMonitor);
    progressMonitor.beginTask(
        FileBuffersMessages.RemoveTrailingWhitespaceOperation_task_generatingChanges, lineCount);
    try {

      MultiTextEditWithProgress multiEdit =
          new MultiTextEditWithProgress(
              FileBuffersMessages.RemoveTrailingWhitespaceOperation_task_applyingChanges);

      for (int i = 0; i < lineCount; i++) {
        if (progressMonitor.isCanceled()) throw new OperationCanceledException();

        IRegion region = document.getLineInformation(i);
        if (region.getLength() == 0) continue;

        int lineStart = region.getOffset();
        int lineExclusiveEnd = lineStart + region.getLength();
        int j = lineExclusiveEnd - 1;
        while (j >= lineStart && Character.isWhitespace(document.getChar(j))) --j;
        ++j;
        if (j < lineExclusiveEnd) multiEdit.addChild(new DeleteEdit(j, lineExclusiveEnd - j));
        progressMonitor.worked(1);
      }

      return multiEdit.getChildrenSize() <= 0 ? null : multiEdit;

    } catch (BadLocationException x) {
      throw new CoreException(
          new Status(
              IStatus.ERROR,
              FileBuffersPlugin.PLUGIN_ID,
              IFileBufferStatusCodes.CONTENT_CHANGE_FAILED,
              "",
              x)); //$NON-NLS-1$
    } finally {
      progressMonitor.done();
    }
  }
예제 #17
0
  /**
   * Tries to add this position into the model. Only positions with more than 3 lines can be taken
   * in. If multiple positions exist on the same line, the longest will be chosen. The shorter ones
   * will be deleted.
   *
   * @param position the position to be added.
   */
  private void addPosition(org.eclipse.jface.text.Position position) {
    org.eclipse.jface.text.IDocument document = sourceViewer.getDocument();
    int lines = 0;
    try {
      lines = document.getNumberOfLines(position.offset, position.length);
    } catch (org.eclipse.jface.text.BadLocationException e) {
      e.printStackTrace();
      return;
    }
    if (lines < 3) {
      return;
    }

    // if a position to add existed on the same line, the longest one will be chosen
    try {
      for (org.eclipse.jface.text.source.projection.ProjectionAnnotation annotationToAdd :
          additions.keySet()) {
        org.eclipse.jface.text.Position positionToAdd = additions.get(annotationToAdd);
        if (document.getLineOfOffset(position.offset)
            == document.getLineOfOffset(positionToAdd.offset)) {
          if (positionToAdd.length < position.length) {
            additions.remove(annotationToAdd);
          } else {
            return;
          }
        }
      }
    } catch (org.eclipse.jface.text.BadLocationException e) {
      return;
    }
    for (org.eclipse.jface.text.source.projection.ProjectionAnnotation annotationInModel :
        oldAnnotations) {
      org.eclipse.jface.text.Position positionInModel =
          projectionAnnotationModel.getPosition(annotationInModel);
      if (position.offset == positionInModel.offset && position.length == positionInModel.length) {
        oldAnnotations.remove(annotationInModel);
        return;
      }
    }

    additions.put(new org.eclipse.jface.text.source.projection.ProjectionAnnotation(), position);
  }
예제 #18
0
 private void createAnnotations(final ISourceNode linecoverage) {
   AnnotationModelEvent event = new AnnotationModelEvent(this);
   clear(event);
   final int firstline = linecoverage.getFirstLine();
   final int lastline = Math.min(linecoverage.getLastLine(), document.getNumberOfLines());
   try {
     for (int l = firstline; l <= lastline; l++) {
       final ILine line = linecoverage.getLine(l);
       if (line.getStatus() != ICounter.EMPTY) {
         final IRegion region = document.getLineInformation(l - 1);
         final CoverageAnnotation ca =
             new CoverageAnnotation(region.getOffset(), region.getLength(), line);
         annotations.add(ca);
         event.annotationAdded(ca);
       }
     }
   } catch (BadLocationException ex) {
     EclEmmaUIPlugin.log(ex);
   }
   fireModelChanged(event);
 }
예제 #19
0
  /**
   * Deletes a line from the document
   *
   * @param i
   */
  public static void deleteLine(IDocument doc, int i) {
    try {
      IRegion lineInformation = doc.getLineInformation(i);
      int offset = lineInformation.getOffset();

      int length = -1;

      if (doc.getNumberOfLines() > i) {
        int nextLineOffset = doc.getLineInformation(i + 1).getOffset();
        length = nextLineOffset - offset;
      } else {
        length = lineInformation.getLength();
      }

      if (length > -1) {
        doc.replace(offset, length, "");
      }
    } catch (BadLocationException e) {
      Log.log(e);
    }
  }
예제 #20
0
  /**
   * Handles a single node when traversing the outline tree. Used recursively.
   *
   * @param node
   * @param document
   * @param parentDepth
   * @param newOutlineInput
   * @return
   */
  private int addNodePosition(
      OutlineNode node, IDocument document, int parentDepth, TexOutlineInput newOutlineInput) {

    // add the Document position
    int beginOffset = 0;
    int length = 0;
    Position position = null;

    try {
      beginOffset = document.getLineOffset(node.getBeginLine() - 1);
      if (node.getEndLine() - 1 == document.getNumberOfLines())
        length = document.getLength() - beginOffset;
      else length = document.getLineOffset(node.getEndLine() - 1) - beginOffset;
      position = new Position(beginOffset, length);
      document.addPosition("__outline", position);
    } catch (BadLocationException bpe) {
      throw new OperationCanceledException();
    } catch (BadPositionCategoryException bpce) {
      throw new OperationCanceledException();
    }
    node.setPosition(position);

    // add node to outline input
    newOutlineInput.addNode(node);

    // iterate through the children
    List<OutlineNode> children = node.getChildren();
    int maxDepth = parentDepth + 1;
    if (children != null) {
      for (Iterator<OutlineNode> iter = children.iterator(); iter.hasNext(); ) {
        int localDepth = addNodePosition(iter.next(), document, parentDepth + 1, newOutlineInput);
        if (localDepth > maxDepth) {
          maxDepth = localDepth;
        }
      }
    }
    return maxDepth;
  }
  private ColorAnnotationModel(
      IDocument document, IFile file, IFeatureProject project, ITextEditor editor) {
    this.document = document;
    this.project = project;
    this.file = file;
    composer = project.getComposer();
    composer.initialize(project);

    docLines = document.getNumberOfLines();
    docLength = document.getLength();

    updateAnnotations(true);

    editor.addPropertyListener(
        new IPropertyListener() {
          @Override
          public void propertyChanged(Object source, int propId) {
            if (propId == IEditorPart.PROP_DIRTY && !((ITextEditor) source).isDirty()) {
              updateAnnotations(true);
            }
          }
        });
  }
예제 #22
0
  /*
   * @see ICompletionProposal#getAdditionalProposalInfo()
   */
  @Override
  public String getAdditionalProposalInfo() {
    try {
      fContext.setReadOnly(true);
      TemplateBuffer templateBuffer;
      try {
        templateBuffer = fContext.evaluate(fTemplate);
      } catch (TemplateException e) {
        return null;
      }

      IDocument document = new Document(templateBuffer.getString());
      IndentUtil.indentLines(document, new LineRange(0, document.getNumberOfLines()), null, null);
      return document.get();

    } catch (BadLocationException e) {
      handleException(
          JavaPlugin.getActiveWorkbenchShell(),
          new CoreException(
              new Status(
                  IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, "", e))); // $NON-NLS-1$
      return null;
    }
  }
  @Override
  public List<Position> calculatePositions(final IDocument document) {
    positions.clear();

    this.lastLineIndex = document.getNumberOfLines();
    this.documentText = document.get();
    preferencesService = Platform.getPreferencesService();
    foldingDistance =
        preferencesService.getInt(
            ProductConstants.PRODUCT_ID_DESIGNER, PreferenceConstants.FOLD_DISTANCE, 0, null);

    if (preferencesService.getBoolean(
        ProductConstants.PRODUCT_ID_DESIGNER, PreferenceConstants.FOLDING_ENABLED, true, null)) {
      Interval interval = GlobalIntervalHandler.getInterval(document);
      if (interval == null) {
        interval = (new HeuristicalIntervalDetector()).buildIntervals(document);
        GlobalIntervalHandler.putInterval(document, interval);
      }
      for (Interval subintervall : interval.getSubIntervals()) {
        recursiveTokens(subintervall);
      }
    }
    return positions;
  }
예제 #24
0
 /*
  * @see org.eclipse.compare.rangedifferencer.IRangeComparator#getRangeCount()
  */
 @Override
 public int getRangeCount() {
   return fDocument.getNumberOfLines();
 }
  /**
   * Guesses the function effected/modified by the patch from local file(newer file).
   *
   * @param patchFileInfo patch file
   * @return array of unique function names
   */
  private String[] guessFunctionNames(PatchFile patchFileInfo) {

    // if this file is new file or removed file, do not guess function files
    // TODO: create an option to include function names on
    // new files or not
    if (patchFileInfo.isNewfile() || patchFileInfo.isRemovedFile()) {
      return new String[] {""};
    }

    String[] fnames = new String[0];
    String editorName = ""; // $NON-NLS-1$

    try {
      IEditorDescriptor ed =
          org.eclipse.ui.ide.IDE.getEditorDescriptor(patchFileInfo.getPath().toOSString());
      editorName = ed.getId().substring(ed.getId().lastIndexOf(".") + 1); // $NON-NLS-1$
    } catch (PartInitException e1) {
      ChangelogPlugin.getDefault()
          .getLog()
          .log(
              new Status(
                  IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e1.getMessage(), e1));
      return new String[0];
    }

    // check if the file type is supported

    // get editor input for target file

    IFileEditorInput fei = new FileEditorInput((IFile) patchFileInfo.getResource());

    SourceEditorInput sei = new SourceEditorInput(patchFileInfo.getStorage());

    MyDocumentProvider mdp = new MyDocumentProvider();
    MyStorageDocumentProvider msdp = new MyStorageDocumentProvider();

    try {
      // get document for target file (one for local file, one for repository storage)
      IDocument doc = mdp.createDocument(fei);
      IDocument olddoc = msdp.createDocument(sei);

      HashMap<String, String> functionNamesMap = new HashMap<String, String>();
      ArrayList<String> nameList = new ArrayList<String>();

      // for all the ranges
      for (PatchRangeElement tpre : patchFileInfo.getRanges()) {

        for (int j = tpre.ffromLine; j <= tpre.ftoLine; j++) {

          String functionGuess = "";
          // add func that determines type of file.
          // right now it assumes it's java file.
          if (tpre.isLocalChange()) {
            if ((j < 0) || (j > doc.getNumberOfLines() - 1)) continue; // ignore out of bound lines
            functionGuess = parseCurrentFunctionAtOffset(editorName, fei, doc.getLineOffset(j));
          } else {
            if ((j < 0) || (j > olddoc.getNumberOfLines() - 1))
              continue; // ignore out of bound lines
            functionGuess = parseCurrentFunctionAtOffset(editorName, sei, olddoc.getLineOffset(j));
          }

          // putting it in hashmap will eliminate duplicate
          // guesses.  We use a list to keep track of ordering which
          // is helpful when trying to document a large set of changes.
          if (functionNamesMap.get(functionGuess) == null) nameList.add(functionGuess);
          functionNamesMap.put(functionGuess, functionGuess);
        }
      }

      // dump all unique func. guesses in the order found
      fnames = new String[nameList.size()];
      fnames = nameList.toArray(fnames);

    } catch (CoreException e) {
      ChangelogPlugin.getDefault()
          .getLog()
          .log(
              new Status(
                  IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e.getMessage(), e));
    } catch (BadLocationException e) {
      ChangelogPlugin.getDefault()
          .getLog()
          .log(
              new Status(
                  IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e.getMessage(), e));
    } catch (Exception e) {
      ChangelogPlugin.getDefault()
          .getLog()
          .log(
              new Status(
                  IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e.getMessage(), e));
      e.printStackTrace();
    }
    return fnames;
  }
  /**
   * This will compute the current block positions. The offset at which computations start is
   * determined by {@link #offset}.
   */
  private void computePositions() {
    deletedAnnotations.clear();
    modifiedAnnotations.clear();
    addedAnnotations.clear();
    deletedAnnotations.addAll(currentAnnotations.keySet());
    for (Iterator<Entry<Annotation, Position>> iterator = currentAnnotations.entrySet().iterator();
        iterator.hasNext(); ) {
      Entry<Annotation, Position> entry = iterator.next();
      final Position position = entry.getValue();
      if (position.getOffset() + position.getLength() < offset) {
        deletedAnnotations.remove(entry.getKey());
      }
    }
    try {
      boolean eof =
          seekChars(
              new char[] {
                RULE_BLOCK_START.charAt(0), HELPER_BLOCK_START.charAt(0),
              });
      int startOffset = offset;
      while (!eof) {
        offset++;
        if (RULE_BLOCK_START.equals(document.get(startOffset, RULE_BLOCK_START.length()))) {

          // Rule detected: computing rule scope using brackets

          eof =
              seekChars(
                  new char[] {
                    '{',
                  });
          offset++;
          IRegion region = editor.getBracketMatcher().match(document, offset);
          if (region != null) {
            offset = region.getOffset() + region.getLength();
            eof =
                seekChars(
                    new char[] {
                      '\n',
                    });
            final int endOffset = offset + 1;
            if (document.getNumberOfLines(startOffset, endOffset - startOffset) > 2) {
              createOrUpdateAnnotation(startOffset, endOffset - startOffset, false);
            }
          }
        } else if (HELPER_BLOCK_START.equals(
            document.get(startOffset, HELPER_BLOCK_START.length()))) {
          offset++;

          // Helper detected, looking for helper end: new rule, new helper or eof

          eof =
              seekChars(
                  new char[] {
                    RULE_BLOCK_START.charAt(0), HELPER_BLOCK_START.charAt(0),
                  });
          while (!(eof
              || RULE_BLOCK_START.equals(document.get(offset, RULE_BLOCK_START.length()))
              || HELPER_BLOCK_START.equals(document.get(offset, HELPER_BLOCK_START.length())))) {
            offset++;
            eof =
                seekChars(
                    new char[] {
                      RULE_BLOCK_START.charAt(0), HELPER_BLOCK_START.charAt(0),
                    });
          }
          eof =
              backwardSeekChars(
                  new char[] {
                    ';',
                  },
                  startOffset);
          eof =
              seekChars(
                  new char[] {
                    '\n',
                  });
          final int endOffset = offset + 1;
          if (document.getNumberOfLines(startOffset, endOffset - startOffset) > 2) {
            createOrUpdateAnnotation(startOffset, endOffset - startOffset, false);
          }
        }
        eof =
            seekChars(
                new char[] {
                  RULE_BLOCK_START.charAt(0), HELPER_BLOCK_START.charAt(0),
                });
        startOffset = offset;
      }
    } catch (BadLocationException e) {
      // Nothing to do
    } catch (IOException e) {
      // Nothing to do
    }
    for (Iterator<Annotation> iterator = deletedAnnotations.iterator(); iterator.hasNext(); ) {
      currentAnnotations.remove(iterator.next());
    }
  }
예제 #27
0
 protected void calculatePositions() {
   edu.ustb.sei.mde.testing.testdefinition.resource.testmodel.ITestmodelTextResource textResource =
       (edu.ustb.sei.mde.testing.testdefinition.resource.testmodel.ITestmodelTextResource)
           editor.getResource();
   org.eclipse.jface.text.IDocument document = sourceViewer.getDocument();
   if (textResource == null || document == null) {
     return;
   }
   org.eclipse.emf.common.util.EList<?> errorList = textResource.getErrors();
   if (errorList != null && errorList.size() > 0) {
     return;
   }
   final java.util.List<org.eclipse.jface.text.Position> positions =
       new java.util.ArrayList<org.eclipse.jface.text.Position>();
   edu.ustb.sei.mde.testing.testdefinition.resource.testmodel.ITestmodelLocationMap locationMap =
       textResource.getLocationMap();
   org.eclipse.emf.ecore.EClass[] foldableClasses =
       textResource.getMetaInformation().getFoldableClasses();
   if (foldableClasses == null) {
     return;
   }
   if (foldableClasses.length < 1) {
     return;
   }
   java.util.List<org.eclipse.emf.ecore.EObject> contents = textResource.getContents();
   org.eclipse.emf.ecore.EObject[] contentArray =
       contents.toArray(new org.eclipse.emf.ecore.EObject[0]);
   java.util.List<org.eclipse.emf.ecore.EObject> allContents = getAllContents(contentArray);
   for (org.eclipse.emf.ecore.EObject nextObject : allContents) {
     boolean isFoldable = false;
     for (org.eclipse.emf.ecore.EClass eClass : foldableClasses) {
       if (nextObject.eClass().equals(eClass)) {
         isFoldable = true;
         break;
       }
     }
     if (!isFoldable) {
       continue;
     }
     int offset = locationMap.getCharStart(nextObject);
     int length = locationMap.getCharEnd(nextObject) + 1 - offset;
     try {
       int lines = document.getNumberOfLines(offset, length);
       if (lines < 2) {
         continue;
       }
     } catch (org.eclipse.jface.text.BadLocationException e) {
       continue;
     }
     length = getOffsetOfNextLine(document, length + offset) - offset;
     if (offset >= 0 && length > 0) {
       positions.add(new org.eclipse.jface.text.Position(offset, length));
     }
   }
   org.eclipse.swt.widgets.Display.getDefault()
       .asyncExec(
           new Runnable() {
             public void run() {
               updateCodefolding(positions);
             }
           });
 }
 /**
  * @return the offset where the last line starts
  * @throws BadLocationException
  */
 public int getLastLineOffset() throws BadLocationException {
   int lastLine = doc.getNumberOfLines() - 1;
   return doc.getLineOffset(lastLine);
 }
 /**
  * @return the length of the current command line (all the currently editable area)
  * @throws BadLocationException
  */
 public int getCommandLineLength() throws BadLocationException {
   int lastLine = doc.getNumberOfLines() - 1;
   return doc.getLineLength(lastLine) - getLastLineReadOnlySize();
 }
  /** Do the actual indentation work. */
  private void doIndent() {
    if (targetEditor == null) {
      return;
    }

    IDocument document = getDocument();

    if (null == document) {
      return;
    }

    Interval rootInterval = GlobalIntervalHandler.getInterval(document);
    if (rootInterval == null) {
      rootInterval = (new HeuristicalIntervalDetector()).buildIntervals(document);
      GlobalIntervalHandler.putInterval(document, rootInterval);
    }
    if (rootInterval == null) {
      return;
    }

    int startLine = -1;
    int endLine = -1;
    if (!selection.isEmpty()) {
      if (selection instanceof TextSelection) {
        TextSelection tSelection = (TextSelection) selection;
        if (tSelection.getLength() != 0) {
          startLine = tSelection.getStartLine();
          endLine = tSelection.getEndLine();
        }
      }
    }
    if (startLine == -1 || endLine == -1) {
      startLine = 0;
      endLine = document.getNumberOfLines() - 1;
    }

    indentArray.clear();
    indentArray.add("");

    int nofLines = endLine - startLine;
    int offset;
    int realOffset;
    int lineLength;
    Interval interval;
    try {
      int regionStartOffset = document.getLineOffset(startLine);
      int regionLength =
          document.getLineOffset(endLine) + document.getLineLength(endLine) - regionStartOffset;
      multiEdit = new MultiTextEdit(regionStartOffset, regionLength);
      RewriteSessionEditProcessor processor =
          new RewriteSessionEditProcessor(
              document, multiEdit, TextEdit.UPDATE_REGIONS | TextEdit.CREATE_UNDO);
      for (int i = nofLines; i >= 0; i--) {
        lineLength = document.getLineLength(startLine + i);
        offset = document.getLineOffset(startLine + i);
        realOffset = getRealLineStart(document, offset, lineLength);
        interval = rootInterval.getSmallestEnclosingInterval(realOffset);
        int indentLevel = lineIndentationLevel(document, realOffset, offset + lineLength, interval);
        setIndentLevel(document, document.getLineOffset(startLine + i), indentLevel);
      }

      performEdits(processor);

    } catch (BadLocationException e) {
      ErrorReporter.logExceptionStackTrace(e);
    }
    return;
  }