/**
   * Returns the closest IStructuredDocumentRegion for the offest and viewer.
   *
   * @param viewer
   * @param documentOffset
   * @return the closest IStructuredDocumentRegion for the offest and viewer.
   */
  public static IStructuredDocumentRegion getStructuredDocumentRegion(
      ITextViewer viewer, int documentOffset) {
    IStructuredDocumentRegion sdRegion = null;
    if (viewer == null || viewer.getDocument() == null) return null;

    int lastOffset = documentOffset;
    IStructuredDocument doc = (IStructuredDocument) viewer.getDocument();
    sdRegion = doc.getRegionAtCharacterOffset(documentOffset);
    while (sdRegion == null && lastOffset >= 0) {
      lastOffset--;
      sdRegion = doc.getRegionAtCharacterOffset(lastOffset);
    }
    return sdRegion;
  }
  private IHyperlink openModule(Node current, ITextViewer textViewer, int offset) {
    while (current != null && !(current instanceof Element)) {
      current = current.getParentNode();
    }
    if (current == null) {
      return null;
    }
    String pathUp = XmlUtils.pathUp(current, 2);
    if (!"modules/module".equals(pathUp)) { // $NON-NLS-1$
      // just in case we are in some random plugin configuration snippet..
      return null;
    }

    ITextFileBuffer buf =
        FileBuffers.getTextFileBufferManager().getTextFileBuffer(textViewer.getDocument());
    if (buf == null) {
      // for repository based poms..
      return null;
    }
    IFileStore folder = buf.getFileStore().getParent();

    String path = XmlUtils.getTextValue(current);
    final String fPath = path;
    // construct IPath for the child pom file, handle relative paths..
    while (folder != null && path.startsWith("../")) { // $NON-NLS-1$
      folder = folder.getParent();
      path = path.substring("../".length()); // $NON-NLS-1$
    }
    if (folder == null) {
      return null;
    }
    IFileStore modulePom = folder.getChild(path);
    if (!modulePom.getName().endsWith("xml")) { // $NON-NLS-1$
      modulePom = modulePom.getChild("pom.xml"); // $NON-NLS-1$
    }
    final IFileStore fileStore = modulePom;
    if (!fileStore.fetchInfo().exists()) {
      return null;
    }
    assert current instanceof IndexedRegion;
    final IndexedRegion region = (IndexedRegion) current;

    return new IHyperlink() {
      public IRegion getHyperlinkRegion() {
        return new Region(region.getStartOffset(), region.getEndOffset() - region.getStartOffset());
      }

      public String getHyperlinkText() {
        return NLS.bind(Messages.PomHyperlinkDetector_open_module, fPath);
      }

      public String getTypeLabel() {
        return "pom-module"; //$NON-NLS-1$
      }

      public void open() {
        openXmlEditor(fileStore);
      }
    };
  }
  /** Select the word at the current selection. Return true if successful, false otherwise. */
  protected boolean matchWord() {

    IDocument doc = fText.getDocument();

    try {

      int pos = fPos;
      char c;

      while (pos >= 0) {
        c = doc.getChar(pos);
        if (!Character.isJavaIdentifierPart(c)) break;
        --pos;
      }

      fStartPos = pos;

      pos = fPos;
      int length = doc.getLength();

      while (pos < length) {
        c = doc.getChar(pos);
        if (!Character.isJavaIdentifierPart(c)) break;
        ++pos;
      }

      fEndPos = pos;

      return true;

    } catch (BadLocationException x) {
    }

    return false;
  }
  public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
    List<ICompletionProposal> result = new ArrayList<ICompletionProposal>();

    try {
      IDocument document = viewer.getDocument();
      ITypedRegion partition = document.getPartition(offset);
      if (isOffsetValidForProposal(document, offset, partition.getOffset())) {
        result.add(
            new CompletionProposal("1 ", offset, 0, 2, null, "1 Heading level 1", null, null));
        result.add(
            new CompletionProposal("1.1 ", offset, 0, 4, null, "1.1 Heading level 2", null, null));
        result.add(
            new CompletionProposal(
                "1.1.1 ", offset, 0, 6, null, "1.1.1 Heading level 3", null, null));
        result.add(
            new CompletionProposal(
                "1.1.1.1 ", offset, 0, 8, null, "1.1.1.1 Heading level 4", null, null));
        result.add(
            new CompletionProposal(
                "1.1.1.1.1 ", offset, 0, 10, null, "1.1.1.1.1 Heading level 5", null, null));
        result.add(
            new CompletionProposal(
                "1.1.1.1.1.1 ", offset, 0, 12, null, "1.1.1.1.1.1 Heading level 6", null, null));
      }
    } catch (BadLocationException e) {
      CoreLog.logError("Content assist error", e);
    }

    if (result.size() > 0) {
      return result.toArray(new ICompletionProposal[result.size()]);
    }

    return null;
  }
  /* (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 static IJavaProject findJavaProject(ITextViewer viewer) {

    if (viewer == null) return null;

    IStructuredModel existingModelForRead =
        StructuredModelManager.getModelManager().getExistingModelForRead(viewer.getDocument());

    if (existingModelForRead == null) return null;

    IJavaProject javaProject = null;
    try {
      String baseLocation = existingModelForRead.getBaseLocation();
      // 20041129 (pa) the base location changed for XML model
      // because of FileBuffers, so this code had to be updated
      // https://bugs.eclipse.org/bugs/show_bug.cgi?id=79686
      IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
      IPath filePath = new Path(baseLocation);
      IProject project = null;
      if (filePath.segmentCount() > 0) {
        project = root.getProject(filePath.segment(0));
      }
      if (project != null) {
        javaProject = JavaCore.create(project);
      }
    } catch (Exception ex) {
      MapperPlugin.getDefault().logException(ex);
    }
    return javaProject;
  }
  protected List<IRegion> getAttributeValueRegions(ITextViewer viewer) {
    List<IRegion> regions = new ArrayList<IRegion>();
    IDocument document = viewer.getDocument();
    int startOffset = 0;
    int endOffset = document.getLength();

    IStructuredDocumentRegion sdRegion = null;

    while (startOffset < endOffset
        && (sdRegion = ContentAssistUtils.getStructuredDocumentRegion(viewer, startOffset))
            != null) {
      ITextRegionList list = sdRegion.getRegions();

      for (int i = 0; list != null && i < list.size(); i++) {
        ITextRegion region = list.get(i);
        if (region.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE) {

          final int regionOffset = sdRegion.getStartOffset() + region.getStart();
          final int regionLength = region.getTextLength();

          regions.add(new Region(regionOffset, regionLength));
        }
      }
      startOffset += sdRegion.getLength();
    }

    return regions;
  }
 private void restorePosition() {
   if (fPosition != null && !fPosition.isDeleted() && fViewer.getDocument() != null) {
     fViewer.setSelectedRange(fPosition.offset, fPosition.length);
     fViewer.revealRange(fPosition.offset, fPosition.length);
   }
   fPosition = null;
 }
  /**
   * Show completions at caret position. If current position does not contain quick fixes look for
   * next quick fix on same line by moving from left to right and restarting at end of line if the
   * beginning of the line is reached.
   *
   * @see org.eclipse.jface.text.quickassist.IQuickAssistAssistant#showPossibleQuickAssists()
   */
  public String showPossibleQuickAssists() {
    fPosition = null;
    fCurrentAnnotations = null;

    if (fViewer == null || fViewer.getDocument() == null)
      // Let superclass deal with this
      return super.showPossibleQuickAssists();

    ArrayList resultingAnnotations = new ArrayList(20);
    try {
      Point selectedRange = fViewer.getSelectedRange();
      int currOffset = selectedRange.x;
      int currLength = selectedRange.y;
      boolean goToClosest = (currLength == 0);

      int newOffset =
          collectQuickFixableAnnotations(fEditor, currOffset, goToClosest, resultingAnnotations);
      if (newOffset != currOffset) {
        storePosition(currOffset, currLength);
        fViewer.setSelectedRange(newOffset, 0);
        fViewer.revealRange(newOffset, 0);
      }
    } catch (BadLocationException e) {
      JavaScriptPlugin.log(e);
    }
    fCurrentAnnotations =
        (Annotation[]) resultingAnnotations.toArray(new Annotation[resultingAnnotations.size()]);

    return super.showPossibleQuickAssists();
  }
Beispiel #10
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;
  }
 /*
  * @see org.eclipse.jface.text.IPainter#paint(int)
  */
 public void paint(int reason) {
   IDocument document = fTextViewer.getDocument();
   if (document == null) {
     deactivate(false);
     return;
   }
   if (!fIsActive) {
     fIsActive = true;
     fTextWidget.addPaintListener(this);
     redrawAll();
   } else if (reason == CONFIGURATION || reason == INTERNAL) {
     redrawAll();
   } else if (reason == TEXT_CHANGE) {
     // redraw current line only
     try {
       IRegion lineRegion =
           document.getLineInformationOfOffset(getDocumentOffset(fTextWidget.getCaretOffset()));
       int widgetOffset = getWidgetOffset(lineRegion.getOffset());
       int charCount = fTextWidget.getCharCount();
       int redrawLength = Math.min(lineRegion.getLength(), charCount - widgetOffset);
       if (widgetOffset >= 0 && redrawLength > 0) {
         fTextWidget.redrawRange(widgetOffset, redrawLength, true);
       }
     } catch (BadLocationException e) {
       // ignore
     }
   }
 }
  /**
   * Compute completion proposals.
   *
   * @param viewer the viewer
   * @param documentOffset the document offset
   * @return the i completion proposal[]
   */
  @Override
  public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
    String text;
    String prefix = "";
    PropertyLabelLexer lexer = null;
    PropertyLabelParser parser = null;
    Collection<ICompletionProposal> result = null;
    int selectionRange = 0;

    try {
      text = viewer.getDocument().get(0, documentOffset);
      lexer = new PropertyLabelLexer(new ANTLRStringStream(text));
      CommonTokenStream tokens = new CommonTokenStream(lexer);

      parser = new PropertyLabelParser(tokens, property, new SimpleStringErrorReporter());
      parser.setValidation(true);
      selectionRange = viewer.getSelectedRange().y;
      parser.label();
      modifiersUsed = parser.getModifiersUsed();
      result = computeCompletions(viewer, parser.getContext(), documentOffset, selectionRange);
    } catch (BadLocationException e) {
      e.printStackTrace();
    } catch (RuntimeException e) {
      modifiersUsed = parser.getModifiersUsed();
      prefix = getPrefix(viewer, documentOffset);
      result = computeCompletions(viewer, parser.getContext(), documentOffset, selectionRange);
    } catch (RecognitionException e) {
      modifiersUsed = parser.getModifiersUsed();
      prefix = getPrefix(viewer, documentOffset);
      result = computeCompletions(viewer, parser.getContext(), documentOffset, selectionRange);
    }

    return result.toArray(new ICompletionProposal[] {});
  }
  @Override
  public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
    ICompletionProposal[] allProposals = super.computeCompletionProposals(viewer, offset);
    List<ICompletionProposal> validProposals =
        new ArrayList<ICompletionProposal>(allProposals.length);
    for (ICompletionProposal proposal : allProposals) {
      if (proposal instanceof ICompletionProposalExtension2) {
        if (!((ICompletionProposalExtension2) proposal)
            .validate(viewer.getDocument(), offset, null)) {
          continue;
        }
      }
      validProposals.add(proposal);
    }
    Collections.sort(
        validProposals,
        new Comparator<ICompletionProposal>() {

          public int compare(ICompletionProposal o1, ICompletionProposal o2) {
            return String.CASE_INSENSITIVE_ORDER.compare(
                o1.getDisplayString(), o2.getDisplayString());
          }
        });
    return validProposals.toArray(new ICompletionProposal[validProposals.size()]);
  }
Beispiel #14
0
  /**
   * Inspects the context of the compilation unit around <code>completionPosition</code> and feeds
   * the collector with proposals.
   *
   * @param viewer the text viewer
   * @param completionPosition the context position in the document of the text viewer
   * @param compilationUnit the compilation unit (may be <code>null</code>)
   */
  public void complete(ITextViewer viewer, int completionPosition, IRubyScript compilationUnit) {
    IDocument document = viewer.getDocument();

    if (!(fContextType instanceof RubyScriptContextType)) return;

    Point selection = viewer.getSelectedRange();

    // remember selected text
    String selectedText = null;
    if (selection.y != 0) {
      try {
        selectedText = document.get(selection.x, selection.y);
      } catch (BadLocationException e) {
      }
    }

    RubyScriptContext context =
        ((RubyScriptContextType) fContextType)
            .createContext(document, completionPosition, selection.y, compilationUnit);
    context.setVariable("selection", selectedText); // $NON-NLS-1$
    int start = context.getStart();
    int end = context.getEnd();
    IRegion region = new Region(start, end - start);

    Template[] templates = RubyPlugin.getDefault().getTemplateStore().getTemplates();

    if (selection.y == 0) {
      for (int i = 0; i != templates.length; i++)
        if (context.canEvaluate(templates[i]))
          fProposals.add(
              new TemplateProposal(
                  templates[i],
                  context,
                  region,
                  RubyPluginImages.get(RubyPluginImages.IMG_OBJS_TEMPLATE)));

    } else {

      if (context.getKey().length() == 0) context.setForceEvaluation(true);

      boolean multipleLinesSelected = areMultipleLinesSelected(viewer);

      for (int i = 0; i != templates.length; i++) {
        Template template = templates[i];
        if (context.canEvaluate(template)
            && template.getContextTypeId().equals(context.getContextType().getId())
            && (!multipleLinesSelected && template.getPattern().indexOf($_WORD_SELECTION) != -1
                || (multipleLinesSelected
                    && template.getPattern().indexOf($_LINE_SELECTION) != -1))) {
          fProposals.add(
              new TemplateProposal(
                  templates[i],
                  context,
                  region,
                  RubyPluginImages.get(RubyPluginImages.IMG_OBJS_TEMPLATE)));
        }
      }
    }
  }
Beispiel #15
0
 public void uninstall() {
   if (isInstalled) {
     textViewer.removeTextInputListener(textInputListener);
     isInstalled = false;
     if (documentListener != null) {
       if (textViewer instanceof ISourceViewerExtension4) {
         ContentAssistantFacade facade =
             ((ISourceViewerExtension4) textViewer).getContentAssistantFacade();
         facade.removeCompletionListener(documentListener);
       }
       if (textViewer.getDocument() instanceof IXtextDocument) {
         ((IXtextDocument) textViewer.getDocument())
             .removeXtextDocumentContentObserver(documentListener);
       }
     }
   }
 }
 static int getLine(final int offset, ITextViewer viewer) {
   int line = -1;
   try {
     line = viewer.getDocument().getLineOfOffset(offset);
   } catch (BadLocationException e) {
     e.printStackTrace();
   }
   return line;
 }
 @Override
 protected TemplateContext createContext(ITextViewer viewer, IRegion region) {
   TemplateContextType contextType = getContextType(viewer, region);
   if (contextType != null) {
     IDocument document = viewer.getDocument();
     return new QvtTemplateContext(contextType, document, region.getOffset(), region.getLength());
   }
   return null;
 }
Beispiel #18
0
 /*
  * @see org.eclipse.swt.dnd.DragSourceListener#dragSetData(org.eclipse.swt.dnd.DragSourceEvent)
  */
 @Override
 public void dragSetData(DragSourceEvent event) {
   IDocument doc = fViewer.getDocument();
   try {
     event.data = doc.get(fSelectionPosition.offset, fSelectionPosition.length);
   } catch (BadLocationException e) {
     event.detail = DND.DROP_NONE;
     event.doit = false;
   }
 }
  protected boolean selectComment(int caretPos) {
    IDocument doc = fText.getDocument();
    int startPos, endPos;

    try {
      int pos = caretPos;
      char c = ' ';

      while (pos >= 0) {
        c = doc.getChar(pos);
        if (c == '\\') {
          pos -= 2;
          continue;
        }
        if (c == Character.LINE_SEPARATOR || c == '\"') {
          break;
        }
        --pos;
      }

      if (c != '\"') {
        return false;
      }

      startPos = pos;

      pos = caretPos;
      int length = doc.getLength();
      c = ' ';

      while (pos < length) {
        c = doc.getChar(pos);
        if (c == Character.LINE_SEPARATOR || c == '\"') {
          break;
        }
        ++pos;
      }
      if (c != '\"') {
        return false;
      }

      endPos = pos;

      int offset = startPos + 1;
      int len = endPos - offset;
      fText.setSelectedRange(offset, len);
      return true;
    } catch (BadLocationException x) {
    }

    return false;
  }
  private String getPrefix(ITextViewer viewer, int offset) throws BadLocationException {
    IDocument doc = viewer.getDocument();
    if (doc == null || offset > doc.getLength()) {
      return null;
    }

    int length = 0;
    while (--offset >= 0 && isPrefixChar(doc.getChar(offset))) {
      length++;
    }

    return doc.get(offset + 1, length);
  }
  /**
   * Extracts the line that is being edited
   *
   * @param viewer
   * @param offset
   * @return
   */
  private String extractEditedLine(ITextViewer viewer, int offset) {
    String result = null;

    IDocument document = viewer.getDocument();
    try {
      int lastEditedLine = document.getLineOfOffset(offset);
      int lineLenght = document.getLineLength(lastEditedLine);
      result = document.get().substring(offset - lineLenght, offset);
      result = result.trim();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }
 private String lineFor(final ITextViewer textViewer, final IRegion region) {
   try {
     return textViewer.getDocument().get(region.getOffset(), region.getLength()).trim();
   } catch (final BadLocationException e) {
     FeatureEditorPlugin.instance()
         .error(
             "Couldn't get line at region ("
                 + region.getOffset()
                 + ", "
                 + region.getLength()
                 + ")");
   }
   return null;
 }
  @Override
  protected List<? extends ICompletionProposal> computeProposals(
      final ITextViewer viewer, final int offset) {
    final IDocument document = viewer.getDocument();
    try {
      final String lineContent =
          DocumentUtilities.lineContentBeforeCurrentPosition(document, offset);
      final boolean shouldShowProposal = shouldShowProposals(lineContent, document, offset);

      if (shouldShowProposal) {
        final boolean isTsv = assist.isTsvFile();
        final Optional<IRegion> region =
            DocumentUtilities.findLiveCellRegion(document, isTsv, offset);
        final String prefix = DocumentUtilities.getPrefix(document, region, offset);
        final String content =
            region.isPresent()
                ? document.get(region.get().getOffset(), region.get().getLength())
                : "";
        final Image image =
            ImagesManager.getImage(RedImages.getImageForFileWithExtension(".robot"));

        final List<RedCompletionProposal> proposals = newArrayList();
        for (final IFile resourceFile : assist.getResourceFiles()) {

          final String resourcePath = resourceFile.getFullPath().makeRelative().toString();
          if (resourcePath.toLowerCase().startsWith(prefix.toLowerCase())) {
            final String resourceRelativePath =
                createCurrentFileRelativePath(resourceFile.getFullPath().makeRelative());
            final RedCompletionProposal proposal =
                RedCompletionBuilder.newProposal()
                    .will(assist.getAcceptanceMode())
                    .theText(resourceRelativePath)
                    .atOffset(offset - prefix.length())
                    .givenThatCurrentPrefixIs(prefix)
                    .andWholeContentIs(content)
                    .thenCursorWillStopAtTheEndOfInsertion()
                    .displayedLabelShouldBe(resourcePath)
                    .currentPrefixShouldBeDecorated()
                    .proposalsShouldHaveIcon(image)
                    .create();
            proposals.add(proposal);
          }
        }
        return proposals;
      }
      return null;
    } catch (final BadLocationException e) {
      return null;
    }
  }
  private static void applyProposal(
      ICompletionProposal proposal,
      ITextViewer viewer,
      char trigger,
      int stateMask,
      final int offset) {
    Assert.isTrue(proposal instanceof ICompletionProposalExtension2);

    IRewriteTarget target = null;
    IEditingSupportRegistry registry = null;
    IEditingSupport helper =
        new IEditingSupport() {

          public boolean isOriginator(DocumentEvent event, IRegion focus) {
            return focus.getOffset() <= offset && focus.getOffset() + focus.getLength() >= offset;
          }

          public boolean ownsFocusShell() {
            return false;
          }
        };

    try {
      IDocument document = viewer.getDocument();

      if (viewer instanceof ITextViewerExtension) {
        ITextViewerExtension extension = (ITextViewerExtension) viewer;
        target = extension.getRewriteTarget();
      }

      if (target != null) target.beginCompoundChange();

      if (viewer instanceof IEditingSupportRegistry) {
        registry = (IEditingSupportRegistry) viewer;
        registry.register(helper);
      }

      ((ICompletionProposalExtension2) proposal).apply(viewer, trigger, stateMask, offset);

      Point selection = proposal.getSelection(document);
      if (selection != null) {
        viewer.setSelectedRange(selection.x, selection.y);
        viewer.revealRange(selection.x, selection.y);
      }
    } finally {
      if (target != null) target.endCompoundChange();

      if (registry != null) registry.unregister(helper);
    }
  }
  /** Match the brackets at the current selection. Return true if successful, false otherwise. */
  protected boolean matchBracketsAt() {

    char prevChar, nextChar;

    int i;
    int bracketIndex1 = fgBrackets.length;
    int bracketIndex2 = fgBrackets.length;

    fStartPos = -1;
    fEndPos = -1;

    // get the chars preceding and following the start position
    try {

      IDocument doc = fText.getDocument();

      prevChar = doc.getChar(fPos - 1);
      nextChar = doc.getChar(fPos);

      // is the char either an open or close bracket?
      for (i = 0; i < fgBrackets.length; i = i + 2) {
        if (prevChar == fgBrackets[i]) {
          fStartPos = fPos - 1;
          bracketIndex1 = i;
        }
      }
      for (i = 1; i < fgBrackets.length; i = i + 2) {
        if (nextChar == fgBrackets[i]) {
          fEndPos = fPos;
          bracketIndex2 = i;
        }
      }

      if (fStartPos > -1 && bracketIndex1 < bracketIndex2) {
        fEndPos = searchForClosingBracket(fStartPos, prevChar, fgBrackets[bracketIndex1 + 1], doc);
        if (fEndPos > -1) return true;
        else fStartPos = -1;
      } else if (fEndPos > -1) {
        fStartPos = searchForOpenBracket(fEndPos, fgBrackets[bracketIndex2 - 1], nextChar, doc);
        if (fStartPos > -1) return true;
        else fEndPos = -1;
      }

    } catch (BadLocationException x) {
    }

    return false;
  }
 @Override
 public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
   try {
     IDocument document = viewer.getDocument();
     ArrayList<ICompletionProposal> result = new ArrayList<ICompletionProposal>();
     String prefix = lastWord(document, offset);
     String indent = lastIndent(document, offset);
     //	    EscriptModel model = EscriptModel.getModel(document, null);
     //	    model.getContentProposals(prefix, indent, offset, result);
     System.out.println(document + " " + prefix + " " + indent);
     return (ICompletionProposal[]) result.toArray(new ICompletionProposal[result.size()]);
   } catch (Exception e) {
     // ... log the exception ...
     return NO_COMPLETIONS;
   }
 }
  protected String extractPrefix(ITextViewer viewer, int offset) {
    int i = offset;
    IDocument document = viewer.getDocument();
    if (i > document.getLength()) return ""; // $NON-NLS-1$

    try {
      while (i > 0) {
        char ch = document.getChar(i - 1);
        if (!Character.isJavaIdentifierPart(ch) && ch != '@') break;
        i--;
      }

      return document.get(i, offset - i);
    } catch (BadLocationException e) {
      return ""; //$NON-NLS-1$
    }
  }
Beispiel #28
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;
    }
  }
Beispiel #29
0
  /**
   * Is the given selection single-line commented?
   *
   * @param selection Selection to check
   * @return <code>true</code> iff all selected lines are commented
   */
  private boolean isSelectionCommented(ISelection selection) {
    if (!(selection instanceof ITextSelection)) return false;

    ITextSelection textSelection = (ITextSelection) selection;
    if (textSelection.getStartLine() < 0 || textSelection.getEndLine() < 0) return false;

    IDocument document = fViewer.getDocument();

    try {

      IRegion block = getTextBlockFromSelection(textSelection, document);
      ITypedRegion[] regions =
          TextUtilities.computePartitioning(
              document, fDocumentPartitioning, block.getOffset(), block.getLength(), false);

      //			int lineCount= 0;
      int[] lines = new int[regions.length * 2]; // [startline, endline, startline, endline, ...]
      for (int i = 0, j = 0; i < regions.length; i++, j += 2) {
        // start line of region
        lines[j] = getFirstCompleteLineOfRegion(regions[i], document);
        // end line of region
        int length = regions[i].getLength();
        int offset = regions[i].getOffset() + length;
        if (length > 0) offset--;
        lines[j + 1] = (lines[j] == -1 ? -1 : document.getLineOfOffset(offset));
        //				lineCount += lines[j + 1] - lines[j] + 1;
      }

      // Perform the check
      for (int i = 0, j = 0; i < regions.length; i++, j += 2) {
        String[] prefixes = fPrefixesMap.get(regions[i].getType());
        if (prefixes != null && prefixes.length > 0 && lines[j] >= 0 && lines[j + 1] >= 0)
          if (!isBlockCommented(lines[j], lines[j + 1], prefixes, document)) return false;
      }

      return true;

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

    return false;
  }
Beispiel #30
0
 /*
  * @see org.eclipse.swt.dnd.DragSourceListener#dragStart(org.eclipse.swt.dnd.DragSourceEvent)
  */
 @Override
 public void dragStart(DragSourceEvent event) {
   if (!fIsEnabled) {
     event.doit = false;
     return;
   }
   // convert screen coordinates to widget offest
   int offset = getOffsetAtLocation(event.x, event.y, false);
   // convert further to a document offset
   offset = getDocumentOffset(offset);
   Point selection = fViewer.getSelectedRange();
   if (selection != null && offset >= selection.x && offset < selection.x + selection.y) {
     fSelectionPosition = new Position(selection.x, selection.y);
     if (fViewer instanceof ITextViewerExtension) {
       ((ITextViewerExtension) fViewer).getRewriteTarget().beginCompoundChange();
     }
     IDocument doc = fViewer.getDocument();
     try {
       // add the drag selection position
       // the position is used to delete the selection on a DROP_MOVE
       // and it can be used by the drop target to determine if it should
       // allow the drop (e.g. if drop location overlaps selection)
       doc.addPositionCategory(DRAG_SELECTION_CATEGORY);
       fPositionUpdater = new DefaultPositionUpdater(DRAG_SELECTION_CATEGORY);
       doc.addPositionUpdater(fPositionUpdater);
       doc.addPosition(DRAG_SELECTION_CATEGORY, fSelectionPosition);
     } catch (BadLocationException e) {
       // should not happen
     } catch (BadPositionCategoryException e) {
       // cannot happen
     }
     event.doit = true;
     // this has no effect?
     event.detail = DND.DROP_COPY;
     if (isDocumentEditable()) {
       event.detail |= DND.DROP_MOVE;
     }
   } else {
     event.doit = false;
     event.detail = DND.DROP_NONE;
   }
 }