Example #1
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;
 }
Example #2
0
  private String normalizeBlockIndentation(ITextSelection selection, String selectedText)
      throws Throwable {
    String[] lines = selectedText.split("\\n");
    if (lines.length < 2) {
      return selectedText;
    }

    String firstLine =
        doc.get(
            doc.getLineOffset(selection.getStartLine()),
            doc.getLineLength(selection.getStartLine()));
    String lineDelimiter = TextUtilities.getDefaultLineDelimiter(doc);

    String indentation = "";
    int bodyIndent = 0;
    while (firstLine.startsWith(" ")) {
      indentation += " ";
      firstLine = firstLine.substring(1);
      bodyIndent += 1;
    }

    if (bodyIndent > 0) {
      StringBuffer selectedCode = new StringBuffer();
      for (String line : lines) {
        if (line.startsWith(indentation)) {
          selectedCode.append(line.substring(bodyIndent) + lineDelimiter);
        } else {
          selectedCode.append(line + lineDelimiter);
        }
      }
      selectedText = selectedCode.toString();
    }
    return selectedText;
  }
Example #3
0
  @Override
  public IFigure getTooltip(Object element) {
    if (element instanceof BasicBlock) {
      BasicBlock bb = (BasicBlock) element;
      IR ir = irView.getIR();
      IDocument doc = irView.getDocument();
      IMethod method = ir.getMethod();

      StringBuffer result = new StringBuffer();

      int start = bb.getFirstInstructionIndex();
      int end = bb.getLastInstructionIndex();
      SSAInstruction[] instructions = ir.getInstructions();
      for (int j = start; j <= end; j++) {
        if (instructions[j] != null) {
          int sourceLineNum = method.getLineNumber(j);
          int lineNumber = sourceLineNum - 1; // IDocument indexing is 0-based
          try {
            int lineOffset = doc.getLineOffset(lineNumber);
            int lineLength = doc.getLineLength(lineNumber);
            String sourceCode = doc.get(lineOffset, lineLength).trim();
            result.append(sourceCode);
          } catch (BadLocationException e) {
          }
          result.append("\n");
        }
      }
      return new Label(result.toString());
    }
    return null;
  }
 private String getIndentOfLine(IDocument d, int line) throws BadLocationException {
   if (line > -1) {
     int start = d.getLineOffset(line);
     int end = start + d.getLineLength(line) - 1;
     int whiteEnd = findEndOfWhiteSpace(d, start, end);
     return d.get(start, whiteEnd - start);
   } else {
     return ""; //$NON-NLS-1$
   }
 }
Example #5
0
 /**
  * Creates Annotations for FOP Composed File
  *
  * @param event
  * @param fstFeature
  * @param m
  * @throws BadLocationException
  */
 private void createFOPComposedAnnotations(
     AnnotationModelEvent event, FSTFeature fstFeature, RoleElement<?> m)
     throws BadLocationException {
   if (m.getComposedLine() <= 0) {
     return;
   }
   int startline = m.getComposedLine() - 1;
   int endline = m.getComposedLine() + m.getMethodLength() - 1;
   int lineOffset = document.getLineOffset(startline);
   int length = 0;
   for (int line = startline; line <= endline; line++) {
     length += document.getLineLength(line);
     // bar at the left of the editor
     Position methodposition =
         new Position(document.getLineOffset(line), document.getLineLength(line));
     ColorAnnotation cafh =
         new ColorAnnotation(
             m.getRole().getFeature().getColor(), methodposition, ColorAnnotation.TYPE_IMAGE);
     cafh.setText(m.getRole().getFeature().getName());
     annotations.add(cafh);
     event.annotationAdded(cafh);
   }
   Position methodposition = new Position(lineOffset, length);
   // bar at the right of the editor
   ColorAnnotation cafho =
       new ColorAnnotation(
           m.getRole().getFeature().getColor(), methodposition, ColorAnnotation.TYPE_OVERVIEW);
   cafho.setText(m.getRole().getFeature().getName());
   annotations.add(cafho);
   event.annotationAdded(cafho);
   if (highlighting) {
     // background colors
     ColorAnnotation cafhh =
         new ColorAnnotation(
             m.getRole().getFeature().getColor(), methodposition, ColorAnnotation.TYPE_HIGHLIGHT);
     cafhh.setText(fstFeature.getName());
     annotations.add(cafhh);
     event.annotationAdded(cafhh);
   }
 }
  /** 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);
  }
Example #7
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);
  }
  /**
   * Extracts the line that is being edited
   *
   * @param viewer
   * @param offset
   * @return
   */
  private String extractEditedLine(ITextViewer viewer, int offset) {
    String result = null;

    IDocument document = viewer.getDocument();
    try {
      int lastEditedLine = document.getLineOfOffset(offset);
      int lineLenght = document.getLineLength(lastEditedLine);
      result = document.get().substring(offset - lineLenght, offset);
      result = result.trim();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }
 /**
  * Extend the selection that the action will work on. Default implementation, extend to whole
  * lines. Might be overridden.
  *
  * @param document text {@link IDocument}
  * @param selection original selection
  * @return new {@link ITextSelection} extended to the whole lines intersected by selection
  */
 public static ITextSelection extendSelectionToWholeLines(
     final IDocument document, final ITextSelection selection) {
   final int startLine = selection.getStartLine();
   final int endLine = selection.getEndLine();
   int startLineOffset;
   try {
     startLineOffset = document.getLineOffset(startLine);
     final int endTextOffset = document.getLineOffset(endLine) + document.getLineLength(endLine);
     return new TextSelection(document, startLineOffset, endTextOffset - startLineOffset);
   } catch (final BadLocationException e) {
     e.printStackTrace();
   }
   return selection;
 }
Example #10
0
 protected Position getFieldNameRange(
     String typeName, String fieldName, IDocument document, IReference reference)
     throws BadLocationException, CoreException {
   int linenumber = reference.getLineNumber();
   if (linenumber > 0) {
     linenumber--;
   }
   if (linenumber > 0) {
     int offset = document.getLineOffset(linenumber);
     String line = document.get(offset, document.getLineLength(linenumber));
     String qname = typeName + "." + fieldName; // $NON-NLS-1$
     int first = line.indexOf(qname);
     if (first < 0) {
       qname = "super." + fieldName; // $NON-NLS-1$
       first = line.indexOf(qname);
     }
     if (first < 0) {
       qname = "this." + fieldName; // $NON-NLS-1$
       first = line.indexOf(qname);
     }
     if (first < 0) {
       // try a pattern [.*fieldname]
       // the field might be ref'd via a constant, e.g. enum constant
       int idx = line.indexOf(fieldName);
       while (idx > -1) {
         if (line.charAt(idx - 1) == '.') {
           first = idx;
           qname = fieldName;
           break;
         }
         idx = line.indexOf(fieldName, idx + 1);
       }
     }
     Position pos = null;
     if (first > -1) {
       pos = new Position(offset + first, qname.length());
     } else {
       // optimistically select the whole line since we can't find the correct variable name and we
       // can't just select
       // the first occurrence
       pos = new Position(offset, line.length());
     }
     return pos;
   }
   return null;
 }
Example #11
0
 /**
  * Searches for the name of a method at the line number specified in the given reference.
  *
  * @param name method name
  * @param document document to search in
  * @param reference provides line number
  * @return method name range
  * @throws CoreException
  */
 protected Position getMethodNameRange(
     boolean isContructor, String name, IDocument document, IReference reference)
     throws CoreException, BadLocationException {
   int linenumber = reference.getLineNumber();
   if (linenumber > 0) {
     linenumber--;
   }
   String methodname = name;
   int idx = methodname.indexOf('$');
   if (idx > -1) {
     methodname = methodname.substring(0, idx);
   }
   idx = methodname.indexOf(Signatures.getLT());
   if (idx > -1) {
     methodname = methodname.substring(0, idx);
   }
   int offset = document.getLineOffset(linenumber);
   String line = document.get(offset, document.getLineLength(linenumber));
   int start = line.indexOf('=');
   if (start < 0) {
     if (isContructor) {
       // new keyword should only be checked if the method is a constructor
       start = line.indexOf("new"); // $NON-NLS-1$
       if (start < 0) {
         start = 0;
       }
     } else {
       start = 0;
     }
   } else {
     char charat = line.charAt(start - 1);
     // make sure its not '==' | '!=' | '<=' | '>='
     if (line.charAt(start + 1) == '=' || charat == '!' || charat == '<' || charat == '>') {
       start = 0;
     }
   }
   int first = findMethodNameStart(methodname, line, start);
   if (first < 0) {
     methodname = "super"; // $NON-NLS-1$
     first = findMethodNameStart(methodname, line, start);
   }
   if (first > -1) {
     return new Position(offset + first, methodname.length());
   }
   return null;
 }
 private void addFoldingRegions(
     Set<Position> regions, IDocumentElementNode[] nodes, IDocument document)
     throws BadLocationException {
   for (int i = 0; i < nodes.length; i++) {
     IDocumentElementNode element = nodes[i];
     int startLine = document.getLineOfOffset(element.getOffset());
     int endLine = document.getLineOfOffset(element.getOffset() + element.getLength());
     if (startLine < endLine) {
       int start = document.getLineOffset(startLine);
       int end = document.getLineOffset(endLine) + document.getLineLength(endLine);
       Position position = new Position(start, end - start);
       regions.add(position);
       fPositionToElement.put(position, element);
     }
     IDocumentElementNode[] children = element.getChildNodes();
     if (children != null) {
       addFoldingRegions(regions, children, document);
     }
   }
 }
Example #13
0
  protected void indentAfterNewLine(final IDocument d, final DocumentCommand c)
      throws BadLocationException {
    final int offset = c.offset;
    String txt = null;
    editor.reconcileNow();
    final IErlElement element = editor.getElementAt(offset, false);
    final IErlMember member = (IErlMember) element;
    if (member != null) {
      final int start = member.getSourceRange().getOffset();
      if (offset >= start) {
        txt = d.get(start, offset - start);
      }
    }
    if (txt == null) {
      txt = "";
    }
    final int lineN = d.getLineOfOffset(offset);
    final int lineOffset = d.getLineOffset(lineN);
    final int lineLength = d.getLineLength(lineN);
    final String oldLine = d.get(offset, lineLength + lineOffset - offset);
    try {
      final IRpcSite b = BackendCore.getBackendManager().getIdeBackend().getRpcSite();
      final int tabw = getTabWidthFromPreferences();

      final Map<String, String> prefs = new TreeMap<String, String>();
      IndentationPreferencePage.addKeysAndPrefs(prefs);
      SmartTypingPreferencePage.addAutoNLKeysAndPrefs(prefs);
      final boolean useTabs = getUseTabsFromPreferences();
      final IndentResult res =
          ErlideIndent.indentLine(b, oldLine, txt, c.text, tabw, useTabs, prefs);

      if (res.isAddNewLine()) {
        c.text += "\n";
      }
      c.text += res.getText();
      c.length += res.getRemoveNext();
    } catch (final Exception e) {
      ErlLogger.warn(e);
    }
  }
 /*
  * (non-Javadoc)
  * @see org.eclipse.pde.api.tools.internal.builder.AbstractProblemDetector#
  * getSourceRange(org.eclipse.jdt.core.IType,
  * org.eclipse.jface.text.IDocument,
  * org.eclipse.pde.api.tools.internal.provisional.builder.IReference)
  */
 @Override
 protected Position getSourceRange(IType type, IDocument document, IReference reference)
     throws CoreException, BadLocationException {
   switch (reference.getReferenceType()) {
     case IReference.T_TYPE_REFERENCE:
       {
         int linenumber = reference.getLineNumber();
         if (linenumber > 0) {
           // line number starts at 0 for the
           linenumber--;
         }
         if (linenumber > 0) {
           int offset = document.getLineOffset(linenumber);
           String line = document.get(offset, document.getLineLength(linenumber));
           String qname = reference.getReferencedTypeName().replace('$', '.');
           int first = line.indexOf(qname);
           if (first < 0) {
             qname = Signatures.getSimpleTypeName(reference.getReferencedTypeName());
             qname = qname.replace('$', '.');
             first = line.indexOf(qname);
           }
           Position pos = null;
           if (first > -1) {
             pos = new Position(offset + first, qname.length());
           } else {
             // optimistically select the whole line since we can't
             // find the correct variable name and we can't just
             // select
             // the first occurrence
             pos = new Position(offset, line.length());
           }
           return pos;
         } else {
           IApiMember apiMember = reference.getMember();
           switch (apiMember.getType()) {
             case IApiElement.FIELD:
               {
                 IApiField field = (IApiField) reference.getMember();
                 return getSourceRangeForField(type, reference, field);
               }
             case IApiElement.METHOD:
               {
                 // reference in a method declaration
                 IApiMethod method = (IApiMethod) reference.getMember();
                 return getSourceRangeForMethod(type, reference, method);
               }
             default:
               break;
           }
           // reference in a type declaration
           ISourceRange range = type.getNameRange();
           Position pos = null;
           if (range != null) {
             pos = new Position(range.getOffset(), range.getLength());
           }
           if (pos == null) {
             return defaultSourcePosition(type, reference);
           }
           return pos;
         }
       }
     case IReference.T_FIELD_REFERENCE:
       {
         int linenumber = reference.getLineNumber();
         if (linenumber > 0) {
           return getFieldNameRange(
               reference.getReferencedTypeName(),
               reference.getReferencedMemberName(),
               document,
               reference);
         }
         // reference in a field declaration
         IApiField field = (IApiField) reference.getMember();
         return getSourceRangeForField(type, reference, field);
       }
     case IReference.T_METHOD_REFERENCE:
       {
         if (reference.getLineNumber() >= 0) {
           String referenceMemberName = reference.getReferencedMemberName();
           String methodName = null;
           boolean isConstructor = Util.isConstructor(referenceMemberName);
           if (isConstructor) {
             methodName =
                 Signatures.getSimpleTypeName(reference.getReferencedTypeName().replace('$', '.'));
           } else {
             methodName = referenceMemberName;
           }
           Position pos = getMethodNameRange(isConstructor, methodName, document, reference);
           if (pos == null) {
             return defaultSourcePosition(type, reference);
           }
           return pos;
         }
         // reference in a method declaration
         IApiMethod method = (IApiMethod) reference.getMember();
         return getSourceRangeForMethod(type, reference, method);
       }
     default:
       return null;
   }
 }
Example #15
0
  /** Creates the color annotations from the FSTDirectives. */
  private void createAnnotations() {
    AnnotationModelEvent event = new AnnotationModelEvent(this);

    for (FSTDirective directive : validDirectiveList) {
      if (directive == null) {
        continue;
      }
      try {
        int startline = directive.getStartLine();
        int endline = getLastChildLine(directive, directive.getEndLine());
        final int color = directive.getColor();
        int overViewStartOffset = document.getLineOffset(startline);
        int overViewLength = 0;
        for (int line = startline; line <= endline; line++) {
          int length = document.getLineLength(line);
          if (line < endline || directive.getEndLength() > 0) {
            int lineOffset = document.getLineOffset(line);

            if (line == directive.getEndLine()) {
              length = directive.getEndLength();
            }
            if (line == startline) {
              lineOffset += directive.getStartOffset();
              length -= directive.getStartOffset();
            }

            if (hasChildAtLine(directive, line)) {
              length = 1;
            }

            if (overViewStartOffset != -1 && hasChildAtLineWithColor(directive, line)) {
              Position overViewPos = new Position(overViewStartOffset, overViewLength);
              createOverViewRuler(event, directive, color, overViewPos);
              overViewStartOffset = -1;
              overViewLength = 0;
            } else if (!hasChildAtLineWithColor(directive, line)) {
              if (overViewStartOffset == -1) {
                overViewStartOffset = document.getLineOffset(line);
              }
              overViewLength += document.getLineLength(line);
            }

            FSTDirective parent = directive.getParent();
            while (parent != null) {
              lineOffset++;
              if (length > 1) {
                length--;
              }
              parent = parent.getParent();
            }
            Position newPos = new Position(lineOffset, length);

            if (!hasChildAtLine(directive, line)) {
              // bar at the left of the editor
              ColorAnnotation ca = new ColorAnnotation(color, newPos, ColorAnnotation.TYPE_IMAGE);
              ca.setText(directive.toString());
              annotations.add(ca);
              event.annotationAdded(ca);
            }
            if (!hasChildAtLine(directive, line)) {
              // bar at the right of the editor

            }
            if (highlighting) {
              // background colors
              ColorAnnotation ca =
                  new ColorAnnotation(color, newPos, ColorAnnotation.TYPE_HIGHLIGHT);
              ca.setText(directive.toDependencyString());
              annotations.add(ca);
              event.annotationAdded(ca);
            }
          }
        }
        if (overViewStartOffset != -1) {
          Position overViewPos = new Position(overViewStartOffset, overViewLength);
          createOverViewRuler(event, directive, color, overViewPos);
          overViewStartOffset = -1;
          overViewLength = 0;
        }
      } catch (BadLocationException e) {
        LogService.getInstance().log(LogLevel.DEBUG, e.getMessage());
      }
    }

    fireModelChanged(event);
  }
  /** Creates the color annotations from the FSTDirectives. */
  private void createAnnotations() {
    AnnotationModelEvent event = new AnnotationModelEvent(this);

    Iterator<FSTDirective> it = validDirectiveList.descendingIterator();
    while (it.hasNext()) {
      FSTDirective dir = it.next();
      try {
        int startline = dir.getStartLine();
        int endline = dir.getEndLine();
        for (int i = startline; i <= endline; i++) {
          if (i < endline || dir.getEndLength() > 0) {
            int lineLength = document.getLineLength(i);
            int lineOffset = document.getLineOffset(i);

            if (i == endline) {
              lineLength = dir.getEndLength();
            }
            if (i == startline) {
              lineOffset += dir.getStartOffset();
              lineLength -= dir.getStartOffset();
            }

            Position newPos = new Position(lineOffset, lineLength);

            if (!annotatedPositions.containsKey(i)) {
              if (!ColorList.isValidColor(dir.getColor())) break;
              ColorAnnotation ca =
                  new ColorAnnotation(
                      dir.getColor(),
                      new Position(lineOffset, lineLength),
                      ColorAnnotation.TYPE_IMAGE);
              annotations.add(ca);
              event.annotationAdded(ca);

              if (highlighting) {
                ca =
                    new ColorAnnotation(
                        dir.getColor(),
                        newPos,
                        i == startline
                            ? ColorAnnotation.TYPE_HIGHLIGHT_OVERVIEW
                            : ColorAnnotation.TYPE_HIGHLIGHT);
                annotations.add(ca);
                event.annotationAdded(ca);
              } else if (i == startline) {
                ca = new ColorAnnotation(dir.getColor(), newPos, ColorAnnotation.TYPE_OVERVIEW);
                annotations.add(ca);
                event.annotationAdded(ca);
              }

              annotatedPositions.put(i, newPos);
            } else if (highlighting) {
              Position oldPos = annotatedPositions.get(i);
              int oldOffset = oldPos.getOffset();
              int oldLength = oldPos.getLength();
              int wholeOffset = oldOffset;
              int wholeLength = oldLength;

              if (oldOffset > lineOffset) {
                ColorAnnotation ca =
                    new ColorAnnotation(
                        dir.getColor(),
                        new Position(lineOffset, oldOffset - lineOffset),
                        ColorAnnotation.TYPE_HIGHLIGHT);
                annotations.add(ca);
                event.annotationAdded(ca);
                wholeOffset = lineOffset;
                wholeLength += oldOffset - lineOffset;
              }
              int newOffset = oldOffset + oldLength;
              int newLength = lineLength - (newOffset - lineOffset);
              if (newLength > 0) {
                newPos.setOffset(newOffset);
                newPos.setLength(newLength);

                ColorAnnotation ca =
                    new ColorAnnotation(dir.getColor(), newPos, ColorAnnotation.TYPE_HIGHLIGHT);
                annotations.add(ca);
                event.annotationAdded(ca);

                wholeLength += newLength;
              }
              annotatedPositions.put(i, new Position(wholeOffset, wholeLength));
            }
          }
        }
      } catch (BadLocationException e) {
        UIPlugin.getDefault().logError(e);
      }
    }

    fireModelChanged(event);
  }
 /**
  * @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();
 }
 /** @return the length of the last line */
 public int getLastLineLength() throws BadLocationException {
   int lastLine = doc.getNumberOfLines() - 1;
   return doc.getLineLength(lastLine);
 }
  /** 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;
  }
    @Override
    public ICompletionProposal[] computeQuickAssistProposals(
        IQuickAssistInvocationContext invocationContext) {
      IAnnotationModel amodel = invocationContext.getSourceViewer().getAnnotationModel();
      IDocument doc = invocationContext.getSourceViewer().getDocument();

      int offset = invocationContext.getOffset();
      Iterator<?> it = amodel.getAnnotationIterator();
      TreeSet<ICompletionProposal> proposalSet =
          new TreeSet<>(
              new Comparator<Object>() {

                @Override
                public int compare(Object o1, Object o2) {
                  if (o1 instanceof ICompletionProposal && o2 instanceof ICompletionProposal) {
                    ICompletionProposal proposal1 = (ICompletionProposal) o1;
                    ICompletionProposal proposal2 = (ICompletionProposal) o2;
                    return proposal1
                        .getDisplayString()
                        .compareToIgnoreCase(proposal2.getDisplayString());
                  }
                  return 0;
                }
              });
      while (it.hasNext()) {
        Object key = it.next();
        if (!(key instanceof SimpleMarkerAnnotation)) {
          if (key instanceof SpellingAnnotation) {
            SpellingAnnotation annotation = (SpellingAnnotation) key;
            if (amodel.getPosition(annotation).overlapsWith(offset, 1)) {
              ICompletionProposal[] proposals = annotation.getSpellingProblem().getProposals();
              for (ICompletionProposal proposal : proposals) {
                proposalSet.add(proposal);
              }
            }
          }
          continue;
        }

        SimpleMarkerAnnotation annotation = (SimpleMarkerAnnotation) key;
        populateDataModelForAnnotation(annotation);
        IMarker marker = annotation.getMarker();

        IMarkerResolution[] mapping = fResMap.get(marker);
        if (mapping != null) {
          Position pos = amodel.getPosition(annotation);
          try {
            int line = doc.getLineOfOffset(pos.getOffset());
            int start = pos.getOffset();
            String delim = doc.getLineDelimiter(line);
            int delimLength = delim != null ? delim.length() : 0;
            int end = doc.getLineLength(line) + start - delimLength;
            if (offset >= start && offset <= end) {
              for (IMarkerResolution markerResolution : mapping) {
                PDECompletionProposal proposal =
                    new PDECompletionProposal(markerResolution, pos, marker);
                if (!proposalSet.contains(proposal)) {
                  proposalSet.add(proposal);
                }
              }
            }
          } catch (BadLocationException e) {
          }
        }
      }

      return proposalSet.toArray(new ICompletionProposal[proposalSet.size()]);
    }
Example #21
0
  public String mergeChangelog(
      String dateLine,
      String functionGuess,
      String defaultContent,
      IEditorPart changelog,
      String changeLogLocation,
      String fileLocation) {

    String fileDetail = formatFileDetail(changeLogLocation, fileLocation);
    IDocument changelog_doc = getDocument(changelog);
    String function = formatFunction(functionGuess);
    boolean multipleEntrySuccess = false;
    String functionSpacer = " "; // $NON-NLS-1$
    if (function.equals(": ")) // $NON-NLS-1$
    functionSpacer = ""; // $NON-NLS-1$
    if (changelog_doc.getLength() > 0) {

      int offset_start = findChangeLogEntry(changelog_doc, dateLine);
      int offset_end = dateLine.length();
      boolean foundFunction = false;

      if (offset_start != -1) {
        int nextChangeEntry = findChangeLogPattern(changelog_doc, offset_start + dateLine.length());
        int functLogEntry = offset_start + dateLine.length();

        while (functLogEntry < nextChangeEntry) {
          int line_length = 0;
          String entry = ""; // $NON-NLS-1$
          try {
            line_length = changelog_doc.getLineOfOffset(functLogEntry);
            entry = changelog_doc.get(functLogEntry, changelog_doc.getLineLength(line_length));
          } catch (BadLocationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          // Look to see if entry already exists for file (will be preceded by "*")
          if (entry.lastIndexOf("* " + fileDetail) > 0) {
            foundFunction = true;
            // Check for the case where the default content (e.g. new or removed file)
            // is being caught again because user has prepared the ChangeLog more than once.
            // In such a case, just return.  We don't need to repeat ourselves.
            if (defaultContent.length() > 0) {
              if (entry.lastIndexOf(defaultContent) > 0) return ""; // $NON-NLS-1$
            }
            int nextFunctLoc = functLogEntry + fileDetail.length() + 2;
            String nextFunc = ""; // $NON-NLS-1$
            try {
              nextFunc = changelog_doc.get(nextFunctLoc, nextChangeEntry - nextFunctLoc);
            } catch (BadLocationException e1) {
              // TODO Auto-generated catch block
              e1.printStackTrace();
            }
            int foundFunc = nextFunc.indexOf("* "); // $NON-NLS-1$
            if (foundFunc > 0) {
              foundFunc--;
              try {
                while (changelog_doc.get(nextFunctLoc + foundFunc, 1).equals("\t") // $NON-NLS-1$
                    || changelog_doc.get(nextFunctLoc + foundFunc, 1).equals("\n")) { // $NON-NLS-1$
                  foundFunc--;
                }
              } catch (BadLocationException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
              }
              functLogEntry = nextFunctLoc + foundFunc + 1;
              break;
            }
          }
          try {
            functLogEntry += changelog_doc.getLineLength(line_length);
          } catch (BadLocationException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
          }
        }
        if (functLogEntry >= nextChangeEntry) {
          functLogEntry = nextChangeEntry - 1;
          try {
            // Get rid of some potential lines containing whitespace only.
            functLogEntry = removeWhitespaceOnlyLines(changelog_doc, functLogEntry);
            while (changelog_doc.get(functLogEntry, 1).equals("\n")) // $NON-NLS-1$
            functLogEntry--;
          } catch (BadLocationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          functLogEntry++;
        }

        if (offset_start != -1) {
          if (foundFunction) {
            try {
              if (!function.equals(": ")) // $NON-NLS-1$
              changelog_doc.replace(
                    functLogEntry,
                    0,
                    "\n"
                        + TAB // $NON-NLS-1$
                        + function
                        + " "); // $NON-NLS-1$
              else
                changelog_doc.replace(
                    functLogEntry, 0, "\n" + TAB // $NON-NLS-1$
                    );
            } catch (BadLocationException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
            ITextEditor edit = (ITextEditor) changelog;
            if (!function.equals(": ")) // $NON-NLS-1$
            edit.selectAndReveal(functLogEntry + function.length() + 3, 0);
            else edit.selectAndReveal(functLogEntry + function.length(), 0);
            multipleEntrySuccess = true;
          } else {
            try {
              changelog_doc.replace(
                  offset_end,
                  0,
                  TAB
                      + "* "
                      + fileDetail
                      + functionSpacer // $NON-NLS-1$
                      + function
                      + functionSpacer
                      + defaultContent
                      + "\n"); //$NON-NLS-1$
            } catch (BadLocationException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }

            ITextEditor edit = (ITextEditor) changelog;
            edit.selectAndReveal(
                offset_end
                    + fileDetail.length()
                    + function.length()
                    + functionSpacer.length() * 2
                    + 3
                    + defaultContent.length(),
                0);
            multipleEntrySuccess = true;
          }
        }
      }
    }

    if (!multipleEntrySuccess) {
      try {
        if (changelog_doc.getLength() > 0) changelog_doc.replace(0, 0, "\n\n"); // $NON-NLS-1$
        changelog_doc.replace(
            0,
            0,
            dateLine
                + TAB
                + "* "
                + fileDetail // $NON-NLS-1$
                + functionSpacer
                + function
                + functionSpacer
                + defaultContent);

        ITextEditor edit = (ITextEditor) changelog;
        edit.selectAndReveal(
            dateLine.length()
                + fileDetail.length()
                + function.length()
                + functionSpacer.length() * 2
                + 3
                + defaultContent.length(),
            0);
      } catch (BadLocationException e) {
        e.printStackTrace();
      }
    }

    return ""; // $NON-NLS-1$
  }