Ejemplo n.º 1
1
  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$
    }
  }
Ejemplo n.º 2
0
  /* (non-Javadoc)
   * @see org.eclipse.jface.text.ITextHoverExtension2#getHoverInfo2(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
   */
  public Object getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) {
    IJavaScriptStackFrame frame = getFrame();
    if (frame != null) {
      IDocument document = textViewer.getDocument();
      if (document != null) {
        try {
          String variableName = document.get(hoverRegion.getOffset(), hoverRegion.getLength());
          IVariable var = findLocalVariable(frame, variableName);
          if (var != null) {
            return var;
          }

          // might be in 'this'
          var = frame.getThisObject();
          try {
            IValue val = var == null ? null : var.getValue();
            if (val != null) {
              IVariable[] vars = val.getVariables();
              for (int i = 0; i < vars.length; i++) {
                if (vars[i].getName().equals(variableName)) {
                  return vars[i];
                }
              }
            }
          } catch (DebugException de) {
            return null;
          }

        } catch (BadLocationException e) {
          return null;
        }
      }
    }
    return null;
  }
 public void focusOnLines(ILocation range) {
   if (range instanceof ILineLocation) {
     ILineLocation lineLocation = (ILineLocation) range;
     // editors count lines from 0, Crucible counts from 1
     final int startLine = lineLocation.getRangeMin() - 1;
     final int endLine = lineLocation.getRangeMax() - 1;
     if (sourceViewer != null) {
       IDocument document = sourceViewer.getDocument();
       if (document != null) {
         try {
           int offset = document.getLineOffset(startLine);
           int length = document.getLineOffset(endLine) - offset;
           StyledText widget = sourceViewer.getTextWidget();
           try {
             widget.setRedraw(false);
             // sourceViewer.revealRange(offset, length);
             // sourceViewer.setSelectedRange(offset, 0);
             sourceViewer.setSelection(new TextSelection(offset, length), true);
           } finally {
             widget.setRedraw(true);
           }
         } catch (BadLocationException e) {
           StatusHandler.log(
               new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID, e.getMessage(), e));
         }
       }
     }
   }
 }
 /**
  * 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;
 }
  protected void endProcessing() {
    super.endProcessing();
    ValidatorStrategy validatorStrategy = getValidatorStrategy();
    if (validatorStrategy != null) {
      validatorStrategy.endProcessing();
    }
    /* single spell-check for everything to ensure that SpellingProblem offsets are correct */
    IReconcilingStrategy spellingStrategy = getSpellcheckStrategy();
    IDocument document = getDocument();
    if (spellingStrategy != null && document != null) {
      spellingStrategy.reconcile(new Region(0, document.getLength()));
    }

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

    if ((getTextViewer() instanceof ISourceViewer)) {
      ISourceViewer sourceViewer = (ISourceViewer) getTextViewer();
      IAnnotationModel annotationModel = sourceViewer.getAnnotationModel();
      for (int i = 0; i < fReconcileListeners.length; i++) {
        fReconcileListeners[i].reconciled(
            document, annotationModel, false, new NullProgressMonitor());
      }
    }
  }
Ejemplo n.º 6
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();
 }
Ejemplo n.º 7
0
 private String getRelativeIndent(int offset) {
   int indent = getStringOrCommentIndent(offset);
   try {
     IRegion lineInfo = document.getLineInformationOfOffset(offset);
     StringBuilder result = new StringBuilder();
     int lineOffset = lineInfo.getOffset();
     for (int i = lineOffset; i < lineOffset + indent; i++) {
       char ch = document.getChar(i);
       if (ch != ' ' && ch != '\t') {
         return "";
       }
     }
     for (int i = lineOffset + indent; ; ) {
       char ch = document.getChar(i++);
       if (ch == ' ' || ch == '\t') {
         result.append(ch);
       } else {
         break;
       }
     }
     return result.toString();
   } catch (BadLocationException e) {
     e.printStackTrace();
     return "";
   }
 }
 /**
  * Resolves the {@link IBreakpoint} from the given editor and ruler information. Returns <code>
  * null</code> if no breakpoint exists or the operation fails.
  *
  * @param editor the editor
  * @param info the current ruler information
  * @return the {@link IBreakpoint} from the current editor position or <code>null</code>
  */
 protected IBreakpoint getBreakpointFromEditor(ITextEditor editor, IVerticalRulerInfo info) {
   IAnnotationModel annotationModel =
       editor.getDocumentProvider().getAnnotationModel(editor.getEditorInput());
   IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput());
   if (annotationModel != null) {
     @SuppressWarnings("unchecked")
     Iterator<Annotation> iterator = annotationModel.getAnnotationIterator();
     while (iterator.hasNext()) {
       Object object = iterator.next();
       if (object instanceof SimpleMarkerAnnotation) {
         SimpleMarkerAnnotation markerAnnotation = (SimpleMarkerAnnotation) object;
         IMarker marker = markerAnnotation.getMarker();
         try {
           if (marker.isSubtypeOf(IBreakpoint.BREAKPOINT_MARKER)) {
             Position position = annotationModel.getPosition(markerAnnotation);
             int line = document.getLineOfOffset(position.getOffset());
             if (line == info.getLineOfLastMouseButtonActivity()) {
               IBreakpoint breakpoint =
                   DebugPlugin.getDefault().getBreakpointManager().getBreakpoint(marker);
               if (breakpoint != null) {
                 return breakpoint;
               }
             }
           }
         } catch (CoreException e) {
         } catch (BadLocationException e) {
         }
       }
     }
   }
   return null;
 }
  /** This method should be called after all the lines received were processed. */
  private void onAfterAllLinesHandled(
      final String finalText,
      final boolean finalAddedParen,
      final int finalStart,
      final int finalOffset,
      final boolean finalAddedCloseParen,
      final String finalIndentString,
      final int finalNewDeltaCaretPosition) {
    boolean shiftsCaret = true;
    String newText = finalText.substring(finalStart, finalText.length());
    if (finalAddedParen) {
      String cmdLine = getCommandLine();
      Document parenDoc = new Document(cmdLine + newText);
      int currentOffset = cmdLine.length() + 1;
      DocCmd docCmd = new DocCmd(currentOffset, 0, "(");
      docCmd.shiftsCaret = true;
      try {
        strategy.customizeParenthesis(parenDoc, docCmd);
      } catch (BadLocationException e) {
        Log.log(e);
      }
      newText = docCmd.text + newText.substring(1);
      if (!docCmd.shiftsCaret) {
        shiftsCaret = false;
        setCaretOffset(finalOffset + (docCmd.caretOffset - currentOffset));
      }
    } else if (finalAddedCloseParen) {
      String cmdLine = getCommandLine();
      String existingDoc = cmdLine + finalText.substring(1);
      int cmdLineOffset = cmdLine.length();
      if (existingDoc.length() > cmdLineOffset) {
        Document parenDoc = new Document(existingDoc);
        DocCmd docCmd = new DocCmd(cmdLineOffset, 0, ")");
        docCmd.shiftsCaret = true;
        boolean canSkipOpenParenthesis;
        try {
          canSkipOpenParenthesis = strategy.canSkipCloseParenthesis(parenDoc, docCmd);
        } catch (BadLocationException e) {
          canSkipOpenParenthesis = false;
          Log.log(e);
        }
        if (canSkipOpenParenthesis) {
          shiftsCaret = false;
          setCaretOffset(finalOffset + 1);
          newText = newText.substring(1);
        }
      }
    }

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

    history.update(getCommandLine());
  }
Ejemplo n.º 10
0
  /**
   * Restores a previously saved selection in the document.
   *
   * <p>If no selection was previously saved, nothing happens.
   *
   * @since 3.0
   */
  protected void restoreSelection() {

    if (!fSelections.isEmpty()) {

      final IDocument document = getDocument();
      final Position position = (Position) fSelections.pop();

      try {
        document.removePosition(fSelectionCategory, position);
        Point currentSelection = getSelectedRange();
        if (currentSelection == null
            || currentSelection.x != position.getOffset()
            || currentSelection.y != position.getLength()) {
          if (position instanceof ColumnPosition && getTextWidget().getBlockSelection()) {
            setSelection(
                new BlockTextSelection(
                    document,
                    document.getLineOfOffset(position.getOffset()),
                    ((ColumnPosition) position).fStartColumn,
                    document.getLineOfOffset(position.getOffset() + position.getLength()),
                    ((ColumnPosition) position).fEndColumn,
                    getTextWidget().getTabs()));
          } else {
            setSelectedRange(position.getOffset(), position.getLength());
          }
        }

        if (fSelections.isEmpty()) clearRememberedSelection();
      } catch (BadPositionCategoryException exception) {
        // Should not happen
      } catch (BadLocationException x) {
        // Should not happen
      }
    }
  }
Ejemplo n.º 11
0
  /**
   * Remembers and returns the current selection. The saved selection can be restored by calling
   * <code>restoreSelection()</code>.
   *
   * @return the current selection
   * @see org.eclipse.jface.text.ITextViewer#getSelectedRange()
   * @since 3.0
   */
  protected Point rememberSelection() {

    final ITextSelection selection = (ITextSelection) getSelection();
    final IDocument document = getDocument();

    if (fSelections.isEmpty()) {
      fSelectionCategory = _SELECTION_POSITION_CATEGORY + hashCode();
      fSelectionUpdater = new NonDeletingPositionUpdater(fSelectionCategory);
      document.addPositionCategory(fSelectionCategory);
      document.addPositionUpdater(fSelectionUpdater);
    }

    try {
      final Position position;
      if (selection instanceof IBlockTextSelection)
        position =
            new ColumnPosition(
                selection.getOffset(),
                selection.getLength(),
                ((IBlockTextSelection) selection).getStartColumn(),
                ((IBlockTextSelection) selection).getEndColumn());
      else position = new Position(selection.getOffset(), selection.getLength());
      document.addPosition(fSelectionCategory, position);
      fSelections.push(position);

    } catch (BadLocationException exception) {
      // Should not happen
    } catch (BadPositionCategoryException exception) {
      // Should not happen
    }

    return new Point(selection.getOffset(), selection.getLength());
  }
 private ITypedRegion getPartition(IDocument doc, int offset) throws BadLocationException {
   ITypedRegion part =
       TextUtilities.getPartition(
           doc, IPropertiesFilePartitions.PROPERTIES_FILE_PARTITIONING, offset, true);
   if (part.getType() == IDocument.DEFAULT_CONTENT_TYPE
       && part.getLength() == 0
       && offset == doc.getLength()
       && offset > 0) {
     // A special case because when cursor at end of document and just after a '=' sign, then we
     // get a DEFAULT content type
     // with a empty region. We rather would get the non-empty 'Value' partition just before that
     // (which has the assignment in it.
     char assign = doc.getChar(offset - 1);
     if (isAssign(assign)) {
       return new TypedRegion(offset - 1, 1, IPropertiesFilePartitions.PROPERTY_VALUE);
     } else {
       // For a similar case but where there's extra spaces after the '='
       ITypedRegion previousPart =
           TextUtilities.getPartition(
               doc, IPropertiesFilePartitions.PROPERTIES_FILE_PARTITIONING, offset - 1, true);
       int previousEnd = previousPart.getOffset() + previousPart.getLength();
       if (previousEnd == offset) {
         // prefer this over a 0 length partition ending at the same location
         return previousPart;
       }
     }
   }
   return part;
 }
 /**
  * @param type Type of the expression leading upto the 'nav' operator
  * @param navOffset Offset of the nav operator (either ']' or '.'
  * @param offset Offset of the cursor where CA was requested.
  * @return
  */
 private Collection<ICompletionProposal> getNavigationProposals(
     IDocument doc, Type type, int navOffset, int offset) {
   try {
     char navOp = doc.getChar(navOffset);
     if (navOp == '.') {
       String prefix = doc.get(navOffset + 1, offset - (navOffset + 1));
       EnumCaseMode caseMode = caseMode(prefix);
       List<TypedProperty> objectProperties =
           typeUtil.getProperties(type, caseMode, BeanPropertyNameMode.HYPHENATED);
       // Note: properties editor itself deals with relaxed names. So it expects the properties
       // here to be returned in hyphenated form only.
       if (objectProperties != null && !objectProperties.isEmpty()) {
         ArrayList<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
         for (TypedProperty prop : objectProperties) {
           double score = FuzzyMatcher.matchScore(prefix, prop.getName());
           if (score != 0) {
             Type valueType = prop.getType();
             String postFix = propertyCompletionPostfix(valueType);
             DocumentEdits edits = new DocumentEdits(doc);
             edits.delete(navOffset + 1, offset);
             edits.insert(offset, prop.getName() + postFix);
             proposals.add(completionFactory.simpleProposal(prop.getName(), score, edits));
           }
         }
         return proposals;
       }
     } else {
       // TODO: other cases ']' or '[' ?
     }
   } catch (Exception e) {
     BootActivator.log(e);
   }
   return Collections.emptyList();
 }
Ejemplo n.º 14
0
  /**
   * Adds a line to the document.
   *
   * @param doc the document
   * @param endLineDelim the delimiter that should be used
   * @param contents what should be added (the end line delimiter may be added before or after those
   *     contents (depending on what are the current contents of the document).
   * @param afterLine the contents should be added after the line specified here.
   */
  public static void addLine(IDocument doc, String endLineDelim, String contents, int afterLine) {
    try {

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

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

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

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

      if (offset >= 0) {
        doc.replace(offset, 0, contents);
      }
    } catch (BadLocationException e) {
      Log.log(e);
    }
  }
Ejemplo n.º 15
0
  /**
   * @param docContents should be == doc.get() (just optimizing if the user already did that
   *     before).
   */
  public static void setOnlyDifferentCode(IDocument doc, String docContents, String newContents) {
    String contents = docContents;
    if (contents == null) {
      contents = doc.get();
    }
    int minorLen;
    int contentsLen = contents.length();
    if (contentsLen > newContents.length()) {
      minorLen = newContents.length();
    } else {
      minorLen = contentsLen;
    }
    int applyFrom = 0;
    for (; applyFrom < minorLen; applyFrom++) {
      if (contents.charAt(applyFrom) == newContents.charAt(applyFrom)) {
        continue;
      } else {
        // different
        break;
      }
    }

    if (applyFrom >= contentsLen) {
      // Document is the same.
      return;
    }
    try {
      doc.replace(applyFrom, contentsLen - applyFrom, newContents.substring(applyFrom));
    } catch (BadLocationException e) {
      Log.log(e);
    }
  }
 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);
   }
 }
Ejemplo n.º 17
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;
  }
Ejemplo n.º 18
0
  /**
   * Checks if the angular bracket at <code>offset</code> is a type parameter bracket.
   *
   * @param offset the offset of the opening bracket
   * @param document the document
   * @param scanner a java heuristic scanner on <code>document</code>
   * @return <code>true</code> if the bracket is part of a type parameter, <code>false</code>
   *     otherwise
   * @since 3.1
   */
  private boolean isTypeParameterBracket(
      int offset, IDocument document, PHPHeuristicScanner scanner) {
    /*
     * type parameter come after braces (closing or opening), semicolons, or
     * after a Type name (heuristic: starts with capital character, or after
     * a modifier keyword in a method declaration (visibility, static,
     * synchronized, final)
     */

    try {
      final IRegion line = document.getLineInformationOfOffset(offset);

      final int prevToken = scanner.previousToken(offset - 1, line.getOffset());
      final int prevTokenOffset = scanner.getPosition() + 1;
      final String previous =
          prevToken == Symbols.TokenEOF
              ? null
              : document.get(prevTokenOffset, offset - prevTokenOffset).trim();

      if (prevToken == Symbols.TokenLBRACE
          || prevToken == Symbols.TokenRBRACE
          || prevToken == Symbols.TokenSEMICOLON
          || prevToken == Symbols.TokenSYNCHRONIZED
          || prevToken == Symbols.TokenSTATIC
          || (prevToken == Symbols.TokenIDENT && isTypeParameterIntroducer(previous))
          || prevToken == Symbols.TokenEOF) {
        return true;
      }
    } catch (final BadLocationException e) {
      return false;
    }

    return false;
  }
Ejemplo n.º 19
0
 private boolean closeOpeningFence(String opening, String closing) {
   if (opening.equals("<")) {
     // only close angle brackets if it's after
     // an uppercase identifier or open fence
     int currOffset = command.offset;
     try {
       // TODO: eat whitespace
       char ch = document.getChar(currOffset - 1);
       if (ch == '{' || ch == '(' || ch == '[' || ch == '<' || ch == ',') {
         return !isJavaIdentifierPart(document.getChar(currOffset));
       }
       while (isJavaIdentifierPart(ch) && --currOffset > 0) {
         ch = document.getChar(currOffset - 1);
       }
       return currOffset < command.offset && isUpperCase(document.getChar(currOffset));
     } catch (BadLocationException e) {
       return false;
     }
   } else {
     if (opening.equals(closing)) {
       return count(opening) % 2 == 0;
     } else {
       return count(opening) >= count(closing);
     }
   }
 }
Ejemplo n.º 20
0
  public void run(IAction action) {
    PyEdit pyEdit = getPyEdit();
    PySelection ps = new PySelection(pyEdit);
    if (ps.getSelLength() != 0) {
      return;
    }
    try {
      IDocument doc = ps.getDoc();
      char c = doc.getChar(ps.getAbsoluteCursorOffset() - 1);
      boolean opening = StringUtils.isOpeningPeer(c);
      boolean closing = org.python.pydev.shared_core.string.StringUtils.isClosingPeer(c);

      if (opening || closing) {
        PythonPairMatcher matcher = new PythonPairMatcher();
        IRegion match = matcher.match(doc, ps.getAbsoluteCursorOffset());
        if (match != null) {
          if (closing) {
            pyEdit.setSelection(match.getOffset() + 1, 0);
          } else { // opening
            pyEdit.setSelection(match.getOffset() + match.getLength(), 0);
          }
        }
      }
    } catch (BadLocationException e) {
      return;
    }
  }
Ejemplo n.º 21
0
  /**
   * Calculates the common scope between the end of one line and the beginning of the next.
   *
   * @param document
   * @param line
   * @param endOfLineScope
   * @return
   * @throws BadLocationException
   */
  private String getScope(IDocument document, int line, String endOfLineScope)
      throws BadLocationException {
    // if this is the last line, just use the scope at the end of it.
    int lines = document.getNumberOfLines();
    if (line + 1 >= lines) {
      return endOfLineScope;
    }

    // now grab the scope at the beginning of the next line...
    IRegion nextLine = document.getLineInformation(line + 1);
    // If the next line is empty, take our end of line scope
    if (nextLine.getLength() == 0) {
      return endOfLineScope;
    }
    String startOfNextLineScope =
        getScopeManager().getScopeAtOffset(document, nextLine.getOffset());

    // Calculate the common prefix between the two!
    StringBuilder builder = new StringBuilder();
    int length = Math.min(endOfLineScope.length(), startOfNextLineScope.length());
    for (int i = 0; i < length; i++) {
      char c = endOfLineScope.charAt(i);
      char o = startOfNextLineScope.charAt(i);
      if (c == o) {
        builder.append(c);
      }
    }
    return builder.toString();
  }
Ejemplo n.º 22
0
  /**
   * Traverses the OutlineNode tree and adds a Position for each node to Document.
   *
   * <p>Also adds the nodes to type lists of the OutlineInput and calculates the tree depth.
   *
   * <p>Old Positions are removed before adding new ones.
   *
   * @param rootNodes
   * @param monitor monitor for the job calling this method
   */
  private void updateDocumentPositions(List<OutlineNode> rootNodes, IProgressMonitor monitor) {
    TexOutlineInput newOutlineInput = new TexOutlineInput(rootNodes);

    IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput());

    // remove previous positions
    try {
      document.removePositionCategory("__outline");
    } catch (BadPositionCategoryException bpce) {
      // do nothing, the category will be added again next, it does not exists the first time
    }

    document.addPositionCategory("__outline");
    pollCancel(monitor);

    // add new positions for nodes and their children
    int maxDepth = 0;
    for (Iterator<OutlineNode> iter = rootNodes.iterator(); iter.hasNext(); ) {
      OutlineNode node = iter.next();
      int localDepth = addNodePosition(node, document, 0, newOutlineInput);

      if (localDepth > maxDepth) {
        maxDepth = localDepth;
      }
      pollCancel(monitor);
    }
    pollCancel(monitor);

    // set the new outline input
    newOutlineInput.setTreeDepth(maxDepth);
    this.outlineInput = newOutlineInput;
  }
  /**
   * 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);
      }
    }
  }
Ejemplo n.º 24
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.");
   }
 }
  protected void setEntireDocumentDirty(IDocument document) {
    super.setEntireDocumentDirty(document);

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

      // if there is a folding strategy then reconcile it
      if (getFoldingStrategy() != null) {
        getFoldingStrategy().reconcile(new Region(0, document.getLength()));
      }
    }
  }
  /** This leaves a bit of a mess e.g. "import " or "from " for some later process to clean up. */
  private void deleteImport(PySelection ps, MarkerAnnotationAndPosition markerInfo)
      throws BadLocationException, CoreException {
    IMarker marker = markerInfo.markerAnnotation.getMarker();

    Integer start = (Integer) marker.getAttribute(IMarker.CHAR_START);
    Integer end = (Integer) marker.getAttribute(IMarker.CHAR_END);
    IDocument doc = ps.getDoc();
    while (start > 0) {
      char c;
      try {
        c = doc.getChar(start - 1);
      } catch (Exception e) {
        break;
      }
      if (c == '\r' || c == '\n') {
        break;
      }
      if (Character.isWhitespace(c) || c == ',') {
        start--;
        continue;
      }
      break;
    }
    ps.setSelection(start, end);
    ps.deleteSelection();
  }
  /** Called when the user selects a proposal */
  public void apply(IDocument document) {
    if (m_Element == null) {
      Display.getCurrent().beep();
      return;
    }

    String replace = getReplaceString();

    try {
      // with replacements of a length of 0, the cursor remains in front of the insert
      // make the replacement at least 1, by replacing the last character
      // this causes the replacement to make the cursor jump to the completion string
      int length = getLength();
      int offset = getOffset();
      if (length == 0) {
        if (offset > 0) {
          // add the previous character to the replacement string
          replace = document.getChar(offset - 1) + replace;
          length = 1;
        }
      }

      document.replace(offset - length, length, replace);
    } catch (BadLocationException e) {
    }
  }
  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
      }
    }
  }
Ejemplo n.º 29
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;
  }
  /**
   * Indents a line with a given indentation level.
   *
   * @param document the document being processed.
   * @param lineStart the offset at which the target line starts
   * @param indentationLevel the indentation level to use
   * @exception BadLocationException if the offset is invalid in this document
   */
  private void setIndentLevel(
      final IDocument document, final int lineStart, final int indentationLevel)
      throws BadLocationException {
    int lastWhiteSpace = lineStart;
    char c;
    while (lastWhiteSpace < document.getLength()) {
      c = document.getChar(lastWhiteSpace);
      if (c == ' ' || c == '\t') {
        lastWhiteSpace++;
      } else {
        break;
      }
    }

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

    if (!document
        .get(lineStart, lastWhiteSpace - lineStart)
        .equals(indentArray.get(indentationLevel))) {
      multiEdit.addChild(
          new ReplaceEdit(
              lineStart, lastWhiteSpace - lineStart, indentArray.get(indentationLevel)));
    }
  }