/**
  * @see com.mulgasoft.emacsplus.commands.EmacsPlusCmdHandler#transform(ITextEditor, IDocument,
  *     ITextSelection, ExecutionEvent)
  */
 @Override
 protected int transform(
     ITextEditor editor, IDocument document, ITextSelection currentSelection, ExecutionEvent event)
     throws BadLocationException {
   int result = getCursorOffset(editor, currentSelection);
   // get the selection encompassing the appropriate set of lines
   ITextSelection selection = getLineSelection(editor, document, currentSelection);
   if (selection != null) {
     int offset = selection.getOffset();
     int endOffset = offset + selection.getLength();
     int begin = document.getLineOfOffset(offset);
     int end = document.getLineOfOffset(endOffset);
     if (begin != end && begin < end) {
       ArrayList<String> alst = new ArrayList<String>();
       IRegion region = document.getLineInformation(begin);
       // get text from point or mark
       alst.add(document.get(offset, region.getLength() - (offset - region.getOffset())));
       for (int i = begin + 1; i < end; i++) {
         region = document.getLineInformation(i);
         // get full line of text
         alst.add(document.get(region.getOffset(), region.getLength()));
       }
       region = document.getLineInformation(end);
       // get text to point or mark
       alst.add(document.get(region.getOffset(), endOffset - region.getOffset()));
       Collections.sort(alst, (getComparator(isUniversalPresent())));
       updateLines(document, selection, alst.toArray(new String[0]));
     } else {
       EmacsPlusUtils.showMessage(editor, NO_REGION, true);
     }
   } else {
     EmacsPlusUtils.showMessage(editor, NO_REGION, true);
   }
   return result;
 }
  /**
   * 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);
    }
  }
 private static int getOffset(IDocument document, int line, int column)
     throws BadLocationException {
   int r = document.getLineInformation(line - 1).getOffset();
   IRegion region = document.getLineInformation(line - 1);
   int lineTabCount =
       calculateTabCountInLine(document.get(region.getOffset(), region.getLength()), column);
   r += (column - 1) - (lineTabCount * getTabWidth()) + lineTabCount;
   return r;
 }
  /**
   * Determines whether each line is prefixed by one of the prefixes.
   *
   * @param startLine Start line in document
   * @param endLine End line in document
   * @param prefixes Possible comment prefixes
   * @param document The document
   * @return <code>true</code> iff each line from <code>startLine</code> to and including <code>
   *     endLine</code> is prepended by one of the <code>prefixes</code>, ignoring whitespace at the
   *     begin of line
   */
  private boolean isBlockCommented(
      int startLine, int endLine, String[] prefixes, IDocument document) {

    try {

      // check for occurrences of prefixes in the given lines
      for (int i = startLine; i <= endLine; i++) {

        IRegion line = document.getLineInformation(i);
        String text = document.get(line.getOffset(), line.getLength());

        int[] found = TextUtilities.indexOf(prefixes, text, 0);

        if (found[0] == -1)
          // found a line which is not commented
          return false;

        String s = document.get(line.getOffset(), found[0]);
        s = s.trim();
        if (s.length() != 0)
          // found a line which is not commented
          return false;
      }

      return true;

    } catch (BadLocationException x) {
      // should not happen
      // FIXME			Activator.getPlugin().log(x);
    }

    return false;
  }
  /**
   * 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();
  }
Beispiel #6
0
  /**
   * Returns the indentation of the line <code>line</code> in <code>document</code>. The returned
   * string may contain pairs of leading slashes that are considered part of the indentation. The
   * space before the asterix in a javadoc-like comment is not considered part of the indentation.
   *
   * @param document the document
   * @param line the line
   * @return the indentation of <code>line</code> in <code>document</code>
   * @throws BadLocationException if the document is changed concurrently
   */
  private static String getCurrentIndent(IDocument document, int line) throws BadLocationException {
    IRegion region = document.getLineInformation(line);
    int from = region.getOffset();
    int endOffset = region.getOffset() + region.getLength();

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

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

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

    return document.get(from, to - from);
  }
  public void collectOccurrenceMatches(
      IJavaScriptElement element, IDocument document, Collection resultingMatches) {
    HashMap lineToLineElement = new HashMap();

    for (Iterator iter = fResult.iterator(); iter.hasNext(); ) {
      ASTNode node = (ASTNode) iter.next();
      int startPosition = node.getStartPosition();
      int length = node.getLength();
      try {
        boolean isException = node == fSelectedName;
        int line = document.getLineOfOffset(startPosition);
        Integer lineInteger = new Integer(line);
        ExceptionOccurrencesGroupKey groupKey =
            (ExceptionOccurrencesGroupKey) lineToLineElement.get(lineInteger);
        if (groupKey == null) {
          IRegion region = document.getLineInformation(line);
          String lineContents = document.get(region.getOffset(), region.getLength()).trim();
          groupKey = new ExceptionOccurrencesGroupKey(element, line, lineContents, isException);
          lineToLineElement.put(lineInteger, groupKey);
        } else if (isException) {
          // the line with the target exception always has the exception icon:
          groupKey.setException(true);
        }
        Match match = new Match(groupKey, startPosition, length);
        resultingMatches.add(match);
      } catch (BadLocationException e) {
        // nothing
      }
    }
  }
Beispiel #8
0
  /**
   * Computes and returns the indentation for a javadoc line. The line must be inside a javadoc
   * comment.
   *
   * @param document the document
   * @param line the line in document
   * @param scanner the scanner
   * @param partition the comment partition
   * @return the indent, or <code>null</code> if not computable
   * @throws BadLocationException
   */
  private static String computeJavadocIndent(
      IDocument document, int line, JavaHeuristicScanner scanner, ITypedRegion partition)
      throws BadLocationException {
    if (line == 0) // impossible - the first line is never inside a javadoc comment
    return null;

    // don't make any assumptions if the line does not start with \s*\* - it might be
    // commented out code, for which we don't want to change the indent
    final IRegion lineInfo = document.getLineInformation(line);
    final int lineStart = lineInfo.getOffset();
    final int lineLength = lineInfo.getLength();
    final int lineEnd = lineStart + lineLength;
    int nonWS = scanner.findNonWhitespaceForwardInAnyPartition(lineStart, lineEnd);
    if (nonWS == JavaHeuristicScanner.NOT_FOUND || document.getChar(nonWS) != '*') {
      if (nonWS == JavaHeuristicScanner.NOT_FOUND) return document.get(lineStart, lineLength);
      return document.get(lineStart, nonWS - lineStart);
    }

    // take the indent from the previous line and reuse
    IRegion previousLine = document.getLineInformation(line - 1);
    int previousLineStart = previousLine.getOffset();
    int previousLineLength = previousLine.getLength();
    int previousLineEnd = previousLineStart + previousLineLength;

    StringBuffer buf = new StringBuffer();
    int previousLineNonWS =
        scanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd);
    if (previousLineNonWS == JavaHeuristicScanner.NOT_FOUND
        || document.getChar(previousLineNonWS) != '*') {
      // align with the comment start if the previous line is not an asterix line
      previousLine = document.getLineInformationOfOffset(partition.getOffset());
      previousLineStart = previousLine.getOffset();
      previousLineLength = previousLine.getLength();
      previousLineEnd = previousLineStart + previousLineLength;
      previousLineNonWS =
          scanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd);
      if (previousLineNonWS == JavaHeuristicScanner.NOT_FOUND) previousLineNonWS = previousLineEnd;

      // add the initial space
      // TODO this may be controlled by a formatter preference in the future
      buf.append(' ');
    }

    String indentation = document.get(previousLineStart, previousLineNonWS - previousLineStart);
    buf.insert(0, indentation);
    return buf.toString();
  }
  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.
    }
  }
 public static int getAbsoluteCursorOffset(IDocument doc, int line, int col) {
   try {
     IRegion offsetR = doc.getLineInformation(line);
     return offsetR.getOffset() + col;
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
 public static String getLineContentsToCursor(IDocument doc, int offset)
     throws BadLocationException {
   int lineOfOffset = doc.getLineOfOffset(offset);
   IRegion lineInformation = doc.getLineInformation(lineOfOffset);
   String lineToCursor =
       doc.get(lineInformation.getOffset(), offset - lineInformation.getOffset());
   return lineToCursor;
 }
 /**
  * Gets line from document.
  *
  * @param i Line number
  * @return String line in String form
  */
 public static String getLine(IDocument doc, int i) {
   try {
     IRegion lineInformation = doc.getLineInformation(i);
     return doc.get(lineInformation.getOffset(), lineInformation.getLength());
   } catch (Exception e) {
     return "";
   }
 }
  /**
   * @return the line where the cursor is (from the cursor position to the end of the line).
   * @throws BadLocationException
   */
  public String getLineContentsFromCursor(int offset) throws BadLocationException {
    int lineOfOffset = doc.getLineOfOffset(offset);
    IRegion lineInformation = doc.getLineInformation(lineOfOffset);

    String lineToCursor =
        doc.get(offset, lineInformation.getOffset() + lineInformation.getLength() - offset);
    return lineToCursor;
  }
Beispiel #14
0
  /**
   * @param markOccurrencesRequest
   * @return true if the annotations were removed and added without any problems and false otherwise
   */
  @Override
  protected synchronized Map<Annotation, Position> getAnnotationsToAddAsMap(
      final BaseEditor baseEditor,
      IAnnotationModel annotationModel,
      MarkOccurrencesRequest markOccurrencesRequest,
      IProgressMonitor monitor)
      throws BadLocationException {
    PyEdit pyEdit = (PyEdit) baseEditor;
    PySourceViewer viewer = pyEdit.getPySourceViewer();
    if (viewer == null || monitor.isCanceled()) {
      return null;
    }
    if (viewer.getIsInToggleCompletionStyle() || monitor.isCanceled()) {
      return null;
    }

    PyMarkOccurrencesRequest pyMarkOccurrencesRequest =
        (PyMarkOccurrencesRequest) markOccurrencesRequest;
    Set<ASTEntry> occurrences = pyMarkOccurrencesRequest.getOccurrences();
    if (occurrences == null) {
      if (DEBUG) {
        System.out.println("Occurrences == null");
      }
      return null;
    }

    IDocument doc = pyEdit.getDocument();
    Map<Annotation, Position> toAddAsMap = new HashMap<Annotation, Position>();
    boolean markOccurrencesInStrings = MarkOccurrencesPreferencesPage.useMarkOccurrencesInStrings();

    // get the annotations to add
    for (ASTEntry entry : occurrences) {
      if (!markOccurrencesInStrings) {
        if (entry.node instanceof Name) {
          Name name = (Name) entry.node;
          if (name.ctx == Name.Artificial) {
            continue;
          }
        }
      }

      SimpleNode node = entry.getNameNode();
      IRegion lineInformation = doc.getLineInformation(node.beginLine - 1);

      try {
        Annotation annotation = new Annotation(getOccurrenceAnnotationsType(), false, "occurrence");
        Position position =
            new Position(
                lineInformation.getOffset() + node.beginColumn - 1,
                pyMarkOccurrencesRequest.getInitialName().length());
        toAddAsMap.put(annotation, position);

      } catch (Exception e) {
        Log.log(e);
      }
    }
    return toAddAsMap;
  }
 private int getStartOfPreviousLine(int offset) throws BadLocationException {
   int line = document.getLineOfOffset(offset);
   IRegion lineInfo;
   do {
     if (line == 0) return 0;
     lineInfo = document.getLineInformation(--line);
   } while (lineInfo.getLength() == 0 || isQuoted(lineInfo.getOffset()));
   return lineInfo.getOffset();
 }
Beispiel #16
0
  /**
   * Formats the given selection
   *
   * @see IFormatter
   */
  public void formatSelection(
      IDocument doc, int[] regionsForSave, IPyEdit edit, PySelection ps, FormatStd formatStd) {
    //        Formatter formatter = new Formatter();
    //        formatter.formatSelection(doc, startLine, endLineIndex, edit, ps);

    @SuppressWarnings({"rawtypes", "unchecked"})
    List<Tuple3<Integer, Integer, String>> replaces = new ArrayList();

    String docContents = doc.get();
    String delimiter = PySelection.getDelimiter(doc);
    IDocument formatted;
    try {
      formatted = new Document(formatAll(formatStd, true, docContents, delimiter));
    } catch (SyntaxErrorException e) {
      return;
    }
    // Actually replace the formatted lines: in our formatting, lines don't change, so, this is OK
    // :)
    try {
      for (int i : regionsForSave) {
        IRegion r = doc.getLineInformation(i);
        int iStart = r.getOffset();
        int iEnd = r.getOffset() + r.getLength();

        String line = PySelection.getLine(formatted, i);
        replaces.add(new Tuple3<Integer, Integer, String>(iStart, iEnd - iStart, line));
      }

    } catch (BadLocationException e) {
      Log.log(e);
      return;
    }

    // Apply the formatting from bottom to top (so that the indexes are still valid).
    Collections.reverse(replaces);
    for (Tuple3<Integer, Integer, String> tup : replaces) {
      try {
        doc.replace(tup.o1, tup.o2, tup.o3);
      } catch (BadLocationException e) {
        Log.log(e);
      }
    }

    if (formatStd.addNewLineAtEndOfFile) {
      try {
        int len = doc.getLength();
        if (len > 0) {
          char lastChar = doc.getChar(len - 1);
          if (lastChar != '\r' && lastChar != '\n') {
            doc.replace(len, 0, PySelection.getDelimiter(doc));
          }
        }
      } catch (Throwable e) {
        Log.log(e);
      }
    }
  }
 /**
  * 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);
 }
  /**
   * @param line the number of the line in the document to get the hash for
   * @return the hash of the line
   * @throws BadLocationException if the line number is invalid
   */
  private Integer getHash(int line) throws BadLocationException {
    Integer hash = fHashes.get(line);
    if (hash == null) {
      IRegion lineRegion = fDocument.getLineInformation(line);
      String lineContents = fDocument.get(lineRegion.getOffset(), lineRegion.getLength());
      hash = new Integer(computeDJBHash(lineContents));
      fHashes.set(line, hash);
    }

    return hash;
  }
  /**
   * 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);
    }
  }
 private int getEndOfPreviousLine(int offset) throws BadLocationException {
   if (offset == document.getLength() && offset > 0) {
     offset--;
   }
   int line = document.getLineOfOffset(offset);
   IRegion lineInfo;
   do {
     if (line == 0) return 0;
     lineInfo = document.getLineInformation(--line);
   } while (lineInfo.getLength() == 0);
   return lineInfo.getOffset() + lineInfo.getLength();
 }
Beispiel #21
0
  protected int endOfLineOf(int offset) throws BadLocationException {

    IRegion info = document.getLineInformationOfOffset(offset);
    if (offset <= info.getOffset() + info.getLength()) return info.getOffset() + info.getLength();

    int line = document.getLineOfOffset(offset);
    try {
      info = document.getLineInformation(line + 1);
      return info.getOffset() + info.getLength();
    } catch (BadLocationException x) {
      return document.getLength();
    }
  }
Beispiel #22
0
 private Position calcExpectedPosition() {
   if (fActiveEditor instanceof ITextEditor) {
     IDocument doc =
         ((ITextEditor) fActiveEditor)
             .getDocumentProvider()
             .getDocument(fActiveEditor.getEditorInput());
     if (doc == null) return null;
     try {
       IRegion region = doc.getLineInformation(fExpectedLine - 1);
       return new Position(region.getOffset(), region.getLength());
     } catch (BadLocationException e) {
     }
   }
   return null;
 }
Beispiel #23
0
  /**
   * Indents line <code>line</code> in <code>document</code> with <code>indent</code>. Leaves
   * leading comment signs alone.
   *
   * @param document the document
   * @param line the line
   * @param indent the indentation to insert
   * @param commentlines
   * @throws BadLocationException on concurrent document modification
   */
  private static void addIndent(
      IDocument document, int line, CharSequence indent, boolean[] commentlines, int relative)
      throws BadLocationException {
    IRegion region = document.getLineInformation(line);
    int insert = region.getOffset();
    int endOffset = region.getOffset() + region.getLength();

    // go behind line comments
    if (!commentlines[relative]) {
      while (insert < endOffset - 2 && document.get(insert, 2).equals(SLASHES)) insert += 2;
    }

    // insert indent
    document.replace(insert, 0, indent.toString());
  }
Beispiel #24
0
  /**
   * Formats the given selection
   *
   * @see IFormatter
   */
  public void formatSelection(
      IDocument doc, int startLine, int endLineIndex, IPyEdit edit, PySelection ps) {
    //        Formatter formatter = new Formatter();
    //        formatter.formatSelection(doc, startLine, endLineIndex, edit, ps);

    try {
      IRegion start = doc.getLineInformation(startLine);
      IRegion end = doc.getLineInformation(endLineIndex);

      int iStart = start.getOffset();
      int iEnd = end.getOffset() + end.getLength();

      String d = doc.get(iStart, iEnd - iStart);
      FormatStd formatStd = getFormat();
      String formatted = formatStr(d, formatStd, PySelection.getDelimiter(doc), false);

      doc.replace(iStart, iEnd - iStart, formatted);

    } catch (BadLocationException e) {
      Log.log(e);
    } catch (SyntaxErrorException e) {
      throw new RuntimeException(e);
    }
  }
Beispiel #25
0
  public static TextSelection determineSelection(
      LinkedList<String> markerFields, IDocument document) throws BadLocationException {
    if (markerFields.size() < 2) throw new IllegalArgumentException();

    int fromLine = Integer.parseInt(markerFields.removeFirst());
    int fromCol = Integer.parseInt(markerFields.removeFirst());
    int toLine = fromLine;
    int toCol = fromCol;
    if (markerFields.size() >= 2
        && isInteger(markerFields.get(0))
        && isInteger(markerFields.get(1))) {
      toLine = Integer.parseInt(markerFields.removeFirst());
      toCol = Integer.parseInt(markerFields.removeFirst());
    }

    IRegion fromLineRegion = document.getLineInformation(fromLine - 1);
    IRegion toLineRegion = document.getLineInformation(toLine - 1);

    int fromOffset = fromLineRegion.getOffset() + fromCol - 1;
    int toOffset = toLineRegion.getOffset() + toCol - 1;
    int length = toOffset - fromOffset;

    return new TextSelection(document, fromOffset, length);
  }
Beispiel #26
0
  public void parse() throws BadLocationException {

    final List<OutlineNodeDefinition<?>> nodeDefinitions =
        configuration.getAllOutlineLevelDefinitions();
    final List<ShowInOutlineInstruction> showInOutlineInstructions =
        configuration.getInstructions(ShowInOutlineInstruction.class);

    String entry = null, header = null;

    for (int lineNumber = 0; lineNumber < numberOfLines; lineNumber++) {

      IRegion region = document.getLineInformation(lineNumber);
      String line = getLine(document, region);

      if (line.equals(MyContentOutlinePage.CONFIG_MARKER) || hasConfigSection) {
        onConfigLine(lineNumber, line, region);
        continue;
      }

      if (ParsingUtils.isLogEntryStart(line)) {
        header = line;
        entry = ParsingUtils.getLogEntry(document, lineNumber);
      }

      onAnyLine(lineNumber, line, entry, header, region);
      if (ParsingUtils.isLogEntryStart(line)) {
        onLogEntryLine(lineNumber, line, entry, region);
      }

      if (showInOutline(showInOutlineInstructions, line, entry, header)) {
        for (OutlineNodeDefinition<?> nodeDefinition : nodeDefinitions) {
          OutlineNodeContent content =
              nodeDefinition.recognize(lineNumber, line, entry, header, region, document);
          if (content != null) {
            @SuppressWarnings({"unchecked", "rawtypes"})
            OutlineNode<?> node =
                new OutlineNode(nodeDefinition, content, region, lineNumber, line, document);
            outlineNodesMap.put(lineNumber, node);
          }
        }
      }
    }

    sortOutlineNodes();
    dumpInfoToConfigSection();
  }
Beispiel #27
0
  /**
   * Returns <code>true</code> if one line is completely selected or if multiple lines are selected.
   * Being completely selected means that all characters except the new line characters are
   * selected.
   *
   * @return <code>true</code> if one or multiple lines are selected
   * @since 2.1
   */
  private boolean areMultipleLinesSelected(ITextViewer viewer) {
    if (viewer == null) return false;

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

    try {

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

    } catch (BadLocationException x) {
      return false;
    }
  }
 /*
  * (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);
   }
 }
 public void switchToJavaEditor(ICompilationUnit unit, int lineNumber) {
   JavaEditor javaEditor = getJavaEditor(unit);
   if (javaEditor != null) {
     IDocument document =
         javaEditor.getDocumentProvider().getDocument(javaEditor.getEditorInput());
     IRegion lineInfo = null;
     try {
       // line count internally starts with 0, and not with 1 like in
       // GUI
       lineInfo = document.getLineInformation(lineNumber - 1);
     } catch (BadLocationException e) {
       // ignored because line number may not really exist in document,
       // we guess this...
     }
     if (lineInfo != null) {
       javaEditor.selectAndReveal(lineInfo.getOffset(), lineInfo.getLength());
     }
   }
 }
  /*
   * @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();
    }
  }