public void run(IProgressMonitor progressMonitor)
      throws InvocationTargetException, InterruptedException {
    try {
      boolean isFixedForm = getFortranEditor().isFixedForm();

      IDocument doc = getFortranEditor().getIDocument();
      Reader in = new StringReader(doc.get());
      Reader cppIn = new CPreprocessingReader(getFortranEditor().getIFile(), null, in);
      try {
        File tempFile =
            File.createTempFile(
                "tmp", //$NON-NLS-1$
                isFixedForm ? ".f" : ".f90"); // $NON-NLS-1$ //$NON-NLS-2$
        tempFile.deleteOnExit();
        PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(tempFile)));
        try {
          for (int c = cppIn.read(); c != -1; c = cppIn.read()) out.print((char) c);
        } finally {
          out.close();
        }

        IDE.openEditor(
            Workbench.getInstance().getActiveWorkbenchWindow().getActivePage(),
            tempFile.toURI(),
            FortranEditor.EDITOR_ID,
            true);
      } finally {
        cppIn.close();
      }
    } catch (Exception e) {
      String message = e.getMessage();
      if (message == null) message = e.getClass().getName();
      MessageDialog.openError(getFortranEditor().getShell(), "Error", message); // $NON-NLS-1$
    }
  }
Example #2
0
 /**
  * Remove any empty lines (i.e. lines only containing whitespace) between <code>offset</code> and
  * index backed-up until a '\n' preceded by some non-whitespace character is reached. Whitespace
  * will be merged to '\n\n'. For example consider the following string "(main): Removed.\n\t\
  * \n\n\t\n" and <code>offset</code> pointing to the last '\n'. This string would be changed to:
  * "(main): Removed.\n\n".
  *
  * @param changelog_doc
  * @param offset
  * @return The new offset.
  */
 private int removeWhitespaceOnlyLines(IDocument changelog_doc, int offset) {
   int initialOffset = offset;
   int backedUpOffset = offset;
   char charAtOffset;
   try {
     charAtOffset = changelog_doc.get(offset, 1).charAt(0);
   } catch (BadLocationException e) {
     e.printStackTrace();
     return offset;
   }
   while (backedUpOffset > 0
       && (charAtOffset == '\n' || charAtOffset == '\t' || charAtOffset == ' ')) {
     backedUpOffset--;
     try {
       charAtOffset = changelog_doc.get(backedUpOffset, 1).charAt(0);
     } catch (BadLocationException e) {
       e.printStackTrace();
       break;
     }
   }
   if ((initialOffset - backedUpOffset) > 2) {
     try {
       int replaceLength = (initialOffset - backedUpOffset - 2);
       changelog_doc.replace(backedUpOffset + 2, replaceLength, "");
       // change offset accordingly
       offset -= replaceLength;
     } catch (BadLocationException e) {
       // exception should have been thrown earlier if that's
       // really a bad location...
     }
   }
   return offset;
 }
 /** Calculates the contents of page 2 when the it is activated. */
 protected void pageChange(int newPageIndex) {
   super.pageChange(newPageIndex);
   if (newPageIndex == 1) {
     IDocument inputDocument =
         xmlEditor.getDocumentProvider().getDocument(xmlEditor.getEditorInput());
     String documentContent = inputDocument.get();
     TSEditor.setDocument(documentContent);
   } else if (newPageIndex == 0) {
     IDocument inputDocument =
         xmlEditor.getDocumentProvider().getDocument(xmlEditor.getEditorInput());
     String documentContent = inputDocument.get();
     if (documentContent.isEmpty()) {
       documentContent = "";
       Bundle bundle = Platform.getBundle("reprotool.ide.txtspec");
       URL url = bundle.getResource("schema/default.txtspec.xml");
       try {
         InputStream ir = url.openStream();
         InputStreamReader isr = new InputStreamReader(ir);
         BufferedReader br = new BufferedReader(isr);
         String append;
         if ((documentContent = (br.readLine())) != null) ;
         while ((append = (br.readLine())) != null) documentContent += ("\n" + append);
         br.close();
       } catch (Exception e) {
         System.err.println(e.getMessage() + " " + e.getCause().toString());
       }
       documentContent = documentContent.trim();
     }
     xmlEditor.setDocument(documentContent);
   }
 }
Example #4
0
  /**
   * Determines whether each line is prefixed by one of the prefixes.
   *
   * @param startLine Start line in document
   * @param endLine End line in document
   * @param prefixes Possible comment prefixes
   * @param document The document
   * @return <code>true</code> iff each line from <code>startLine</code> to and including <code>
   *     endLine</code> is prepended by one of the <code>prefixes</code>, ignoring whitespace at the
   *     begin of line
   */
  private boolean isBlockCommented(
      int startLine, int endLine, String[] prefixes, IDocument document) {

    try {

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

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

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

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

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

      return true;

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

    return false;
  }
  /*
   * (non-Javadoc)
   *
   * @see com.cea.accordcpp.core.ui.panels.AccordAbstractPanel#checkModifications()
   */
  @Override
  public boolean checkModifications() {
    String ptrValue = StereotypeUtil.isApplied(selectedParameter, Ptr.class) ? "*" : "";
    if (!docPtr.get().equals(ptrValue)) {
      return true;
    }

    String refValue = StereotypeUtil.isApplied(selectedParameter, Ref.class) ? "&" : "";
    if (!docRef.get().equals(refValue)) {
      return true;
    }

    String defaultValue = selectedParameter.getDefault();
    if (defaultValue == null) {
      if (!docDefault.get().equals("")) {
        return true;
      }
    } else if (!docDefault.get().equals(defaultValue)) {
      return true;
    }

    String arrayValue = StereotypeUtil.isApplied(selectedParameter, Array.class) ? "[]" : "";
    if (!docArray.get().equals(arrayValue)) {
      return true;
    }
    return false;
  }
Example #6
0
 /**
  * @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;
 }
Example #7
0
 @Override
 public void customizeDocumentCommand(IDocument d, DocumentCommand c) {
   try {
     if ("-".equals(c.text) && c.offset >= 3 && d.get(c.offset - 3, 3).equals("<!-")) {
       c.text = "-  -->";
       c.shiftsCaret = false;
       c.caretOffset = c.offset + 2;
       c.doit = false;
       return;
     }
     if ("[".equals(c.text) && c.offset >= 2 && d.get(c.offset - 2, 2).equals("<!")) {
       c.text = "[CDATA[]]>";
       c.shiftsCaret = false;
       c.caretOffset = c.offset + 7;
       c.doit = false;
       return;
     }
     if ("l".equals(c.text) && c.offset >= 4 && d.get(c.offset - 4, 4).equals("<?xm")) {
       c.text = "l version = \"1.0\" encoding = \"" + charset + "\"?>";
       return;
     }
   } catch (BadLocationException e) {
     HTMLPlugin.logException(e);
   }
   super.customizeDocumentCommand(d, c);
 }
  @Override
  public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
    clearAnnotations();

    if (oldInput != null) {
      IDocument document = documentProvider.getDocument(oldInput);
      if (document != null) {
        try {
          document.removePositionCategory(SEGMENTS);
        } catch (BadPositionCategoryException e) {
          // Do Nothing
        }
        document.removePositionUpdater(positionUpdater);
      }
    }

    if (newInput != null) {
      IDocument document = documentProvider.getDocument(newInput);
      if (document != null) {
        document.addPositionCategory(SEGMENTS);
        document.addPositionUpdater(positionUpdater);

        tree = parser.parse(document.get());
        addAnnotations(document.get());
      }
    }
  }
Example #9
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);
  }
  /**
   * @return the current token and its initial offset for this token
   * @param the chars to be considered separators (note that whitespace chars are always considered
   *     separators and don't need to be in this set).
   * @throws BadLocationException
   */
  public Tuple<String, Integer> getCurrToken(Set<Character> separatorChars)
      throws BadLocationException {
    int offset = getAbsoluteCursorOffset();
    int i = offset;

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

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

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

    String prefix = tup.o1;

    // ok, now, get the rest of the token, as we already have its prefix
    int start = tup.o2 - prefix.length();
    int end = start;
    while (doc.getLength() - 1 >= end) {
      char ch = doc.getChar(end);
      if (separatorChars.contains(ch) || Character.isWhitespace(ch)) {
        break;
      }
      end++;
    }
    String post = doc.get(tup.o2, end - tup.o2);
    return new Tuple<String, Integer>(prefix + post, start);
  }
  private boolean terminateWithSemicolon() throws Exception {
    final IDocument doc = editor.getCeylonSourceViewer().getDocument();
    final TextChange change = new DocumentChange("Terminate Statement", doc);
    change.setEdit(new MultiTextEdit());
    CeylonParseController parser = parse();
    CompilationUnit rootNode = parser.getRootNode();
    IRegion li = getLineInfo(doc);
    String lineText = doc.get(li.getOffset(), li.getLength());
    final List<CommonToken> tokens = parser.getTokens();
    // final int startOfCodeInLine = getCodeStart(li, lineText, tokens);
    final int endOfCodeInLine = getCodeEnd(li, lineText, tokens);
    if (!doc.get(endOfCodeInLine, 1).equals(";")) {
      new Processor() {
        @Override
        public void visit(Tree.Annotation that) {
          super.visit(that);
          terminateWithSemicolon(that);
        }

        @Override
        public void visit(Tree.StatementOrArgument that) {
          super.visit(that);
          if (that instanceof Tree.ExecutableStatement && !(that instanceof Tree.ControlStatement)
              || that instanceof Tree.AttributeDeclaration
              || that instanceof Tree.MethodDeclaration
              || that instanceof Tree.ClassDeclaration
              || that instanceof Tree.InterfaceDeclaration
              || that instanceof Tree.SpecifiedArgument) {
            terminateWithSemicolon(that);
          }
        }

        private void terminateWithSemicolon(Node that) {
          try {
            if (that.getStartIndex() <= endOfCodeInLine && that.getStopIndex() >= endOfCodeInLine) {
              Token et = that.getEndToken();
              if (et == null
                  || et.getType() != CeylonLexer.SEMICOLON
                  || that.getStopIndex() > endOfCodeInLine) {
                if (!change.getEdit().hasChildren()) {
                  change.addEdit(new InsertEdit(endOfCodeInLine + 1, ";"));
                }
              }
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }.visit(rootNode);
      if (change.getEdit().hasChildren()) {
        change.perform(new NullProgressMonitor());
        return true;
      }
    }
    return false;
  }
 protected String getSurroundingText(IDocument document, int offset, int context) {
   int start = (offset - context < 0) ? 0 : offset - context;
   int end =
       (offset + context > document.getLength() - 1) ? document.getLength() - 1 : offset + context;
   try {
     return document.get(start, offset - start) + "|" + document.get(offset, end - (offset + 1));
   } catch (BadLocationException e) {
     return StringUtil.EMPTY;
   }
 }
Example #13
0
  boolean unpairedClose(char openingChar, char closingCharacter, IDocument document, int offset) {
    try {
      // Now we need to do smarter checks, see if rest of doc contains unbalanced set!
      String before =
          document.get(0, offset); // don't cheat and trim because we need offsets to match for
      // comment scope matching
      int stackLevel = 0;
      for (int i = 0; i < before.length(); i++) {

        char c = before.charAt(i);
        if (c == openingChar && openingChar == closingCharacter) {
          if (!fgCommentSelector.matches(getScopeAtOffset(document, i))) {
            stackLevel++;
            stackLevel = stackLevel % 2;
          }
        } else if (c == openingChar) {
          if (!fgCommentSelector.matches(getScopeAtOffset(document, i))) {
            stackLevel++;
          }
        } else if (c == closingCharacter) {
          if (!fgCommentSelector.matches(getScopeAtOffset(document, i))) {
            stackLevel--;
          }
        }
      }

      String after =
          document.get(
              offset, document.getLength() - offset); // don't cheat and trim because we need
      // offsets to match for comment scope
      // matching
      for (int i = 0; i < after.length(); i++) {
        char c = after.charAt(i);
        if (c == openingChar && openingChar == closingCharacter) {
          if (!fgCommentSelector.matches(getScopeAtOffset(document, offset + i))) {
            stackLevel++;
            stackLevel = stackLevel % 2;
          }
        } else if (c == openingChar) {
          if (!fgCommentSelector.matches(getScopeAtOffset(document, offset + i))) {
            stackLevel++;
          }
        } else if (c == closingCharacter) {
          if (!fgCommentSelector.matches(getScopeAtOffset(document, offset + i))) {
            stackLevel--;
            if (stackLevel < 0) return true;
          }
        }
      }
      return stackLevel != 0;
    } catch (BadLocationException e) {
      // ignore
    }
    return false;
  }
Example #14
0
 private void reduceIndentOfCurrentLine() throws BadLocationException {
   int spaces = getIndentSpaces();
   String text = document.get(command.offset - spaces, spaces);
   if (endsWithSpaces(text, spaces)) {
     command.offset = command.offset - spaces;
     command.length = spaces;
   } else if (document.get(command.offset - 1, 1).equals("\t")) {
     command.offset = command.offset - 1;
     command.length = 1;
   }
 }
  /**
   * @param theDoc
   * @param documentOffset
   * @return
   * @throws BadLocationException
   */
  public static int eatFuncCall(IDocument theDoc, int documentOffset) throws BadLocationException {
    String c = theDoc.get(documentOffset, 1);
    if (c.equals(")") == false) {
      throw new AssertionError("Expecting ) to eat callable. Received: " + c);
    }

    while (documentOffset > 0 && theDoc.get(documentOffset, 1).equals("(") == false) {
      documentOffset -= 1;
    }

    return documentOffset;
  }
Example #16
0
  /**
   * Add enclosing comment tags for the whole area to be commented
   *
   * @param commentArea initial comment area which can be adjusted
   * @param lastPartition last partition
   * @param doc document
   * @param factory Edit factory
   * @param edits List of edits to update the document
   * @return new possibly adjusted comment area
   * @throws BadLocationException
   */
  private Region handleEnclosingPartitions(
      Region commentArea,
      ITypedRegion lastPartition,
      IDocument doc,
      Edit.EditFactory factory,
      List<Edit> edits)
      throws BadLocationException {

    int commentAreaStart = commentArea.getOffset();
    int commentAreaEnd = commentArea.getOffset() + commentArea.getLength();

    String commentStartTag = getCommentStart(); // "/*"
    String commentEndTag = getCommentEnd(); // "*/"

    String startLineEOL = doc.getLineDelimiter(doc.getLineOfOffset(commentAreaStart));
    if (startLineEOL == null) startLineEOL = ""; // $NON-NLS-1$
    String endLineEOL = doc.getLineDelimiter(doc.getLineOfOffset(commentAreaEnd - 1));
    if (endLineEOL == null) endLineEOL = ""; // $NON-NLS-1$

    boolean isLeftEol =
        commentAreaStart < startLineEOL.length()
            || doc.get(commentAreaStart - startLineEOL.length(), startLineEOL.length())
                .equals(startLineEOL);
    boolean isRightEol =
        doc.get(commentAreaEnd - endLineEOL.length(), endLineEOL.length()).equals(endLineEOL);

    if (isLeftEol && isRightEol) {
      // Block of full lines found
      int areaStartLine = doc.getLineOfOffset(commentAreaStart + startLineEOL.length());
      int areaEndLine = doc.getLineOfOffset(commentAreaEnd - endLineEOL.length());
      if (areaStartLine != areaEndLine) {
        // If multiple full lines arrange inserting comment tags on their own lines
        commentStartTag = getCommentStart() + startLineEOL;
        commentEndTag = getCommentEnd() + endLineEOL;
      } else {
        // If one full line insert end comment tag on the same line (before the EOL)
        commentAreaEnd = commentAreaEnd - endLineEOL.length();
      }
    } else {
      if (lastPartition.getType() == ICPartitions.C_SINGLE_LINE_COMMENT
          || lastPartition.getType() == ICPartitions.C_SINGLE_LINE_DOC_COMMENT) {
        // C++ comments "//" partition ends with EOL, insert end comment tag before it
        // on the same line, so we get something like /*// text*/
        commentAreaEnd = commentAreaEnd - endLineEOL.length();
      }
    }

    edits.add(factory.createEdit(commentAreaStart, 0, commentStartTag));
    edits.add(factory.createEdit(commentAreaEnd, 0, commentEndTag));

    return new Region(commentAreaStart, commentAreaEnd - commentAreaStart);
  }
 /**
  * Returns the valid Java identifier in a document immediately before the given offset.
  *
  * @param document the document
  * @param offset the offset at which to start looking
  * @return the Java identifier preceding this location or a blank string if none
  */
 private String lastWord(IDocument document, int offset) {
   try {
     for (int n = offset - 1; n >= 0; n--) {
       char c = document.getChar(n);
       if (!Character.isJavaIdentifierPart(c)) {
         return document.get(n + 1, offset - n - 1);
       }
     }
     return document.get(0, offset);
   } catch (BadLocationException e) {
     Activator.log(e);
   }
   return ""; //$NON-NLS-1$
 }
  public void testSingleNonUIThreadUpdatesToEditorDocument() throws Exception {
    IFile file = getOrCreateFile(PROJECT_NAME + "/" + "testBackgroundChanges.xml");
    ITextFileBufferManager textFileBufferManager = FileBuffers.getTextFileBufferManager();
    textFileBufferManager.connect(
        file.getFullPath(), LocationKind.IFILE, new NullProgressMonitor());

    ITextFileBuffer textFileBuffer =
        textFileBufferManager.getTextFileBuffer(file.getFullPath(), LocationKind.IFILE);
    final IDocument document = textFileBuffer.getDocument();
    document.replace(0, 0, "<?xml encoding=\"UTF-8\" version=\"1.0\"?>\n");
    textFileBuffer.commit(new NullProgressMonitor(), true);

    String testText = document.get() + "<c/><b/><a/>";
    final int end = document.getLength();
    IWorkbenchPage activePage =
        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
    IEditorPart openedEditor = IDE.openEditor(activePage, file);

    final boolean state[] = new boolean[] {false};
    Job changer =
        new Job("text changer") {
          protected IStatus run(IProgressMonitor monitor) {
            try {
              document.replace(end, 0, "<a/>");
              document.replace(end, 0, "<b/>");
              document.replace(end, 0, "<c/>");
            } catch (Exception e) {
              return new Status(IStatus.ERROR, SSEUIPlugin.ID, e.getMessage());
            } finally {
              state[0] = true;
            }
            return Status.OK_STATUS;
          }
        };
    changer.setUser(true);
    changer.setSystem(false);
    changer.schedule();

    while (!state[0]) {
      openedEditor.getSite().getShell().getDisplay().readAndDispatch();
    }

    String finalText = document.get();
    textFileBuffer.commit(new NullProgressMonitor(), true);
    textFileBufferManager.disconnect(
        file.getFullPath(), LocationKind.IFILE, new NullProgressMonitor());
    activePage.closeEditor(openedEditor, false);
    assertEquals("Non-UI changes did not apply", testText, finalText);
  }
  private int computeIndentCount(IDocument document, int offset) {
    try {
      if (offset == document.getLength()) {
        return 0;
      }

      IFile file = EditorUtil.getFile(editor);
      if (file == null) {
        KotlinLogger.logError("Failed to retrieve IFile from editor " + editor, null);
        return 0;
      }

      if (document.get().contains(LineEndUtil.CARRIAGE_RETURN_STRING)) {
        offset -= document.getLineOfOffset(offset);
      }

      PsiFile parsedDocument = KotlinPsiManager.getKotlinFileIfExist(file, document.get());
      if (parsedDocument == null) {
        return 0;
      }

      PsiElement leaf = parsedDocument.findElementAt(offset);
      if (leaf == null) {
        return 0;
      }

      if (leaf.getNode().getElementType() != JetTokens.WHITE_SPACE) {
        leaf = parsedDocument.findElementAt(offset - 1);
      }

      int indent = 0;

      ASTNode node = null;
      if (leaf != null) {
        node = leaf.getNode();
      }
      while (node != null) {
        indent = AlignmentStrategy.updateIndent(node, indent);
        node = node.getTreeParent();
      }

      return indent;
    } catch (BadLocationException e) {
      KotlinLogger.logAndThrow(e);
    }

    return 0;
  }
 private String getReferencesSource(IFile refFile) throws CoreException {
   FileEditorInput input = new FileEditorInput(refFile);
   FileDocumentProvider provider = new FileDocumentProvider();
   provider.connect(input);
   IDocument document = provider.getDocument(input);
   return document.get();
 }
 /**
  * This will update lists {@link #deletedAnnotations}, {@link #addedAnnotations} and {@link
  * #modifiedAnnotations} according to the given values.
  *
  * @param newOffset Offset of the text we want the annotation updated of.
  * @param newLength Length of the text we want the annotation updated of.
  * @param initiallyCollapsed Indicates that the created annotation should be folded from start.
  * @throws BadLocationException Thrown if we try and get an out of range character. Should not
  *     happen.
  */
 private void createOrUpdateAnnotation(
     final int newOffset, final int newLength, boolean initiallyCollapsed)
     throws BadLocationException {
   boolean createAnnotation = true;
   final Map<Annotation, Position> copy = new HashMap<Annotation, Position>(currentAnnotations);
   final String text = document.get(newOffset, newLength);
   for (Iterator<Entry<Annotation, Position>> iterator = copy.entrySet().iterator();
       iterator.hasNext(); ) {
     Entry<Annotation, Position> entry = iterator.next();
     if (entry.getKey().getText().equals(text)) {
       createAnnotation = false;
       final Position oldPosition = entry.getValue();
       if (oldPosition.getOffset() != newOffset || oldPosition.getLength() != newLength) {
         final Position newPosition = new Position(newOffset, newLength);
         modifiedAnnotations.put(entry.getKey(), newPosition);
         currentAnnotations.put(entry.getKey(), newPosition);
       }
       deletedAnnotations.remove(entry.getKey());
       break;
     }
   }
   if (createAnnotation) {
     Annotation annotation = null;
     annotation = new ProjectionAnnotation(initiallyCollapsed);
     annotation.setText(text);
     final Position position = new Position(newOffset, newLength);
     currentAnnotations.put(annotation, position);
     addedAnnotations.put(annotation, position);
   }
 }
Example #22
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;
  }
 public void apply(final IDocument document) {
   IProject p = marker.getResource().getProject();
   IFile f = BuildWrapperPlugin.getCabalFile(p);
   IDocumentProvider prov = new TextFileDocumentProvider();
   try {
     prov.connect(f);
     IDocument doc = prov.getDocument(f);
     PackageDescription pd = PackageDescriptionLoader.load(f);
     int length = pd.getStanzas().size();
     for (int a = 0; a < length; a++) {
       PackageDescriptionStanza pds = pd.getStanzas().get(a);
       CabalSyntax cs = pds.getType();
       if (CabalSyntax.SECTION_EXECUTABLE.equals(cs)
           || CabalSyntax.SECTION_LIBRARY.equals(cs)
           || CabalSyntax.SECTION_TESTSUITE.equals(cs)) {
         RealValuePosition rvp = pds.addToPropertyList(CabalSyntax.FIELD_BUILD_DEPENDS, pkg);
         if (rvp != null) {
           rvp.updateDocument(doc);
           pd = PackageDescriptionLoader.load(doc.get());
         }
       }
     }
     prov.saveDocument(new NullProgressMonitor(), f, doc, true);
   } catch (CoreException ce) {
     HaskellUIPlugin.log(ce);
   }
 }
Example #24
0
  /* (non-Javadoc)
   * @see org.eclipse.jface.text.ITextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
   */
  public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
    ScriptStackFrame frame = getFrame();
    if (frame == null) {
      return null;
    }
    IDocument document = textViewer.getDocument();
    if (document == null) {
      return null;
    }
    try {
      String str =
          TextUtilities.getContentType(
              document,
              IDocumentExtension3.DEFAULT_PARTITIONING,
              hoverRegion.getOffset() + 1,
              true);

      String variableName = document.get(hoverRegion.getOffset(), hoverRegion.getLength());

      if (JSPartitionScanner.JS_KEYWORD.equals(str) && !"this".equals(variableName)) // $NON-NLS-1$
      {
        return null;
      }
      ScriptValue var = ((ScriptDebugTarget) frame.getDebugTarget()).evaluate(frame, variableName);
      if (var != null) {
        return getVariableText(var);
      }
    } catch (BadLocationException e) {
      return null;
    }
    return null;
  }
 protected void addExpressionStyles(int lineOffset, int lineLenght, Vector<StyleRange> styles) {
   final String content = document.get();
   for (Expression exp : expressions) {
     if (supportedTypes.keySet().contains(exp.getType())) {
       try {
         int i = lineOffset;
         IRegion index = null;
         index = finder.find(i, exp.getName(), true, true, true, false);
         while (index != null && index.getOffset() < lineOffset + lineLenght) {
           if (PatternLineStyleListener.isNotEscapeWord(content, index.getOffset())) {
             styles.add(
                 new StyleRange(
                     index.getOffset(),
                     index.getLength(),
                     Display.getDefault().getSystemColor(supportedTypes.get(exp.getType())),
                     null,
                     SWT.BOLD));
           }
           i = index.getOffset() + index.getLength();
           if (i < lineOffset + lineLenght) {
             index = finder.find(i, exp.getName(), true, true, true, false);
           } else {
             index = null;
           }
         }
       } catch (BadLocationException e) {
         // Ignore
       }
     }
   }
 }
  /**
   * Executes the actual work of reseting the given elements document.
   *
   * @param element the element
   * @param monitor the progress monitor
   * @throws CoreException if resetting fails
   * @since 3.0
   */
  protected void doResetDocument(Object element, IProgressMonitor monitor) throws CoreException {
    ElementInfo info = (ElementInfo) fElementInfoMap.get(element);
    if (info != null) {

      IDocument original = null;
      IStatus status = null;

      try {
        original = createDocument(element);
      } catch (CoreException x) {
        status = x.getStatus();
      }

      info.fStatus = status;

      if (original != null) {
        fireElementContentAboutToBeReplaced(element);
        info.fDocument.set(original.get());
        if (info.fCanBeSaved) {
          info.fCanBeSaved = false;
          addUnchangedElementListeners(element, info);
        }
        fireElementContentReplaced(element);
        fireElementDirtyStateChanged(element, false);
      }
    }
  }
 /**
  * Returns the variable and function names at the current line, or <code>null</code> if none.
  *
  * @param part text editor
  * @param selection text selection
  * @return the variable and function names at the current line, or <code>null</code> if none. The
  *     array has two elements, the first is the variable name, the second is the function name.
  */
 protected String[] getVariableAndFunctionName(IWorkbenchPart part, ISelection selection) {
   ITextEditor editor = getEditor(part);
   if (editor != null && selection instanceof ITextSelection) {
     ITextSelection textSelection = (ITextSelection) selection;
     IDocumentProvider documentProvider = editor.getDocumentProvider();
     try {
       documentProvider.connect(this);
       IDocument document = documentProvider.getDocument(editor.getEditorInput());
       IRegion region = document.getLineInformationOfOffset(textSelection.getOffset());
       String string = document.get(region.getOffset(), region.getLength()).trim();
       if (string.startsWith("var ")) { // $NON-NLS-1$
         String varName = string.substring(4).trim();
         String fcnName =
             getFunctionName(
                 document, varName, document.getLineOfOffset(textSelection.getOffset()));
         return new String[] {varName, fcnName};
       }
     } catch (CoreException e) {
     } catch (BadLocationException e) {
     } finally {
       documentProvider.disconnect(this);
     }
   }
   return null;
 }
Example #28
0
 /**
  * Saves the code folding state to a XML file in the state location.
  *
  * @param uriString the key to determine the file to save to
  */
 public void saveCodeFoldingStateFile(String uriString) {
   org.eclipse.jface.text.IDocument document = sourceViewer.getDocument();
   if (document == null) {
     return;
   }
   org.eclipse.ui.XMLMemento codeFoldingMemento = org.eclipse.ui.XMLMemento.createWriteRoot(MODEL);
   codeFoldingMemento.putString(VERIFY_KEY, makeMD5(document.get()));
   saveCodeFolding(codeFoldingMemento);
   java.io.File stateFile = getCodeFoldingStateFile(uriString);
   if (stateFile == null) {
     return;
   }
   try {
     java.io.FileOutputStream stream = new java.io.FileOutputStream(stateFile);
     java.io.OutputStreamWriter writer = new java.io.OutputStreamWriter(stream, "utf-8");
     codeFoldingMemento.save(writer);
     writer.close();
   } catch (java.io.IOException e) {
     stateFile.delete();
     org.eclipse.jface.dialogs.MessageDialog.openError(
         (org.eclipse.swt.widgets.Shell) null,
         "Saving Problems",
         "Unable to save code folding state.");
   }
 }
 private String getContent(int offset, int length) {
   try {
     return document.get(offset, length);
   } catch (BadLocationException e) {
     return "<<<n/a>>>";
   }
 }
  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
      }
    }
  }