Java 类org.eclipse.jface.text.TextUtilities 实例源码

项目:DarwinSPL    文件:DwprofileToggleCommentHandler.java   
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
    }
    return false;
}
项目:DarwinSPL    文件:HyexpressionToggleCommentHandler.java   
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
    }
    return false;
}
项目:DarwinSPL    文件:HyvalidityformulaToggleCommentHandler.java   
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
    }
    return false;
}
项目:DarwinSPL    文件:HydatavalueToggleCommentHandler.java   
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
    }
    return false;
}
项目:DarwinSPL    文件:HymappingToggleCommentHandler.java   
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
    }
    return false;
}
项目:DarwinSPL    文件:HyconstraintsToggleCommentHandler.java   
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
    }
    return false;
}
项目:DarwinSPL    文件:HymanifestToggleCommentHandler.java   
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
    }
    return false;
}
项目:eclipse.jdt.ls    文件:GetterSetterCompletionProposal.java   
/**
 * @param document
 * @param offset
 * @param importRewrite
 * @param completionSnippetsSupported
 * @return
 * @throws CoreException
 * @throws BadLocationException
 */
public String updateReplacementString(IDocument document, int offset, ImportRewrite importRewrite, boolean completionSnippetsSupported) throws CoreException, BadLocationException {
    int flags= Flags.AccPublic | (fField.getFlags() & Flags.AccStatic);

    String stub;
    if (fIsGetter) {
        String getterName= GetterSetterUtil.getGetterName(fField, null);
        stub = GetterSetterUtil.getGetterStub(fField, getterName, true, flags);
    } else {
        String setterName= GetterSetterUtil.getSetterName(fField, null);
        stub = GetterSetterUtil.getSetterStub(fField, setterName, true, flags);
    }

    // use the code formatter
    String lineDelim= TextUtilities.getDefaultLineDelimiter(document);
    String replacement = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, stub, 0, lineDelim, fField.getJavaProject());

    if (replacement.endsWith(lineDelim)) {
        replacement = replacement.substring(0, replacement.length() - lineDelim.length());
    }

    return replacement;
}
项目:eclipse.jdt.ls    文件:JavadocTagsSubProcessor.java   
@Override
protected void addEdits(IDocument document, TextEdit rootEdit) throws CoreException {
    try {
        String lineDelimiter= TextUtilities.getDefaultLineDelimiter(document);
        final IJavaProject project= getCompilationUnit().getJavaProject();
        IRegion region= document.getLineInformationOfOffset(fInsertPosition);

        String lineContent= document.get(region.getOffset(), region.getLength());
        String indentString= Strings.getIndentString(lineContent, project);
        String str= Strings.changeIndent(fComment, 0, project, indentString, lineDelimiter);
        InsertEdit edit= new InsertEdit(fInsertPosition, str);
        rootEdit.addChild(edit);
        if (fComment.charAt(fComment.length() - 1) != '\n') {
            rootEdit.addChild(new InsertEdit(fInsertPosition, lineDelimiter));
            rootEdit.addChild(new InsertEdit(fInsertPosition, indentString));
        }
    } catch (BadLocationException e) {
        throw new CoreException(StatusFactory.newErrorStatus("Invalid edit", e));
    }
}
项目:angular-eclipse    文件:TypeScriptAngularTemplateCompletionProposalComputer.java   
@Override
protected TemplateEngine computeCompletionEngine(TypeScriptContentAssistInvocationContext context) {
    try {
        IResource resource = context.getResource();
        if (resource == null || !AngularProject.isAngularProject(resource.getProject())) {
            return null;
        }
        String partition = TextUtilities.getContentType(context.getDocument(),
                IJavaScriptPartitions.JAVA_PARTITIONING, context.getInvocationOffset(), true);
        if (partition.equals(IJavaScriptPartitions.JAVA_DOC)) {
            return null;
        } else {
            return ng2TemplateEngine;
        }
    } catch (BadLocationException x) {
        return null;
    }
}
项目:fluentmark    文件:AbstractMarksHandler.java   
private boolean samePartition(int beg, int len) throws BadLocationException {
    if (len == 0) return TextUtilities.getContentType(doc, Partitions.MK_PARTITIONING, cpos, false)
            .equals(IDocument.DEFAULT_CONTENT_TYPE);

    boolean begDef = TextUtilities.getContentType(doc, Partitions.MK_PARTITIONING, beg, false)
            .equals(IDocument.DEFAULT_CONTENT_TYPE);
    boolean endDef = TextUtilities.getContentType(doc, Partitions.MK_PARTITIONING, beg + len - 1, false)
            .equals(IDocument.DEFAULT_CONTENT_TYPE);

    if (begDef && endDef) {
        ITypedRegion begRegion = TextUtilities.getPartition(doc, Partitions.MK_PARTITIONING, beg, false);
        ITypedRegion endRegion = TextUtilities.getPartition(doc, Partitions.MK_PARTITIONING, beg + len - 1, false);
        if (begRegion.getOffset() == endRegion.getOffset()) return true;
    }
    return false;
}
项目:fluentmark    文件:ToggleHiddenCommentHandler.java   
private int checkPartition(IDocument doc, int beg, int len) {
    try {
        boolean begCmt = TextUtilities.getContentType(doc, Partitions.MK_PARTITIONING, beg, false)
                .equals(Partitions.COMMENT);
        boolean endCmt = TextUtilities.getContentType(doc, Partitions.MK_PARTITIONING, beg + len - 1, false)
                .equals(Partitions.COMMENT);

        if (begCmt && endCmt) {
            ITypedRegion begPar = TextUtilities.getPartition(doc, Partitions.MK_PARTITIONING, beg, false);
            ITypedRegion endPar = TextUtilities.getPartition(doc, Partitions.MK_PARTITIONING, beg + len - 1, false);
            if (begPar.getOffset() == endPar.getOffset()) return SAME;
            return DIFF;
        }
        if ((begCmt && !endCmt) || (!begCmt && endCmt)) return LAPD;
        return NONE;
    } catch (BadLocationException e) {
        Log.error("Bad comment partitioning " + e.getMessage());
        return UNKN;
    }
}
项目:fluentmark    文件:ToggleHiddenCommentHandler.java   
private void removeComment(IDocument doc, int offset) {
    try {
        IDocumentUndoManager undoMgr = DocumentUndoManagerRegistry.getDocumentUndoManager(doc);
        undoMgr.beginCompoundChange();

        ITypedRegion par = TextUtilities.getPartition(doc, Partitions.MK_PARTITIONING, offset, false);
        int beg = par.getOffset();
        int len = par.getLength();

        String comment = doc.get(beg, len);
        int eLen = markerLen(comment);
        int bLen = eLen + 1;

        MultiTextEdit edit = new MultiTextEdit();
        edit.addChild(new DeleteEdit(beg, bLen));
        edit.addChild(new DeleteEdit(beg + len - eLen, eLen));
        edit.apply(doc);
        undoMgr.endCompoundChange();
    } catch (MalformedTreeException | BadLocationException e) {
        Log.error("Failure removing comment " + e.getMessage());
    }
}
项目:fluentmark    文件:LineWrapEditStrategy.java   
@Override
public void customizeDocumentCommand(final IDocument doc, final DocumentCommand cmd) {
    if (cmd.length != 0 || cmd.text == null) return;

    try {
        if (TextUtilities.endsWith(doc.getLegalLineDelimiters(), cmd.text) != -1) {
            if (AutoEdit.isBlankLine(doc, cmd.offset)) {
                int beg = AutoEdit.getLineOffset(doc, cmd.offset);
                int len = cmd.offset - beg;

                DeleteEdit blanks = new DeleteEdit(beg, len);
                blanks.apply(doc);
                cmd.offset = beg;

            } else {
                autoIndent(doc, cmd, false);    // return entered
            }

        } else if (evaluateInsertPoint(doc, cmd)) {
            autoIndent(doc, cmd, true);     // insert point exceeds limit
        } else if (evaluateLineWidth(doc, cmd)) {
            wrapLines(doc, cmd);            // line end exceeds limit
        }
    } catch (BadLocationException e) {}
}
项目:typescript.java    文件:ReactTemplateCompletionProposalComputer.java   
@Override
protected TemplateEngine computeCompletionEngine(TypeScriptContentAssistInvocationContext context) {
    try {
        if (!TypeScriptResourceUtil.isTsxOrJsxFile(context.getResource())) {
            return null;
        }
        String partition = TextUtilities.getContentType(context.getDocument(),
                IJavaScriptPartitions.JAVA_PARTITIONING, context.getInvocationOffset(), true);
        if (partition.equals(IJavaScriptPartitions.JAVA_DOC)) {
            return null;
        } else if (partition.equals(IJSXPartitions.JSX)) {
            return null;
        } else {
            return reactTemplateEngine;
        }
    } catch (BadLocationException x) {
        return null;
    }
}
项目:typescript.java    文件:JSDocAutoIndentStrategy.java   
private String createMethodTags(IDocument document, DocumentCommand command, String indentation,
        String lineDelimiter, IFunction method) throws CoreException, BadLocationException {
    IRegion partition = TextUtilities.getPartition(document, fPartitioning, command.offset, false);
    IFunction inheritedMethod = getInheritedMethod(method);
    String comment = CodeGeneration.getMethodComment(method, inheritedMethod, lineDelimiter);
    if (comment != null) {
        comment = comment.trim();
        boolean javadocComment = comment.startsWith("/**"); //$NON-NLS-1$
        if (!isFirstComment(document, command, method, javadocComment))
            return null;
        boolean isJavaDoc = partition.getLength() >= 3 && document.get(partition.getOffset(), 3).equals("/**"); //$NON-NLS-1$
        if (javadocComment == isJavaDoc) {
            return prepareTemplateComment(comment, indentation, method.getJavaScriptProject(), lineDelimiter);
        }
    }
    return null;
}
项目:typescript.java    文件:JSDocAutoIndentStrategy.java   
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {

        if (!isSmartMode())
            return;

        if (command.text != null) {
            if (command.length == 0) {
                String[] lineDelimiters = document.getLegalLineDelimiters();
                int index = TextUtilities.endsWith(lineDelimiters, command.text);
                if (index > -1) {
                    // ends with line delimiter
                    if (lineDelimiters[index].equals(command.text))
                        // just the line delimiter
                        indentAfterNewLine(document, command);
                    return;
                }
            }

            if (command.text.equals("/")) { //$NON-NLS-1$
                indentAfterCommentEnd(document, command);
                return;
            }
        }
    }
项目:bts    文件:AbstractPartitionDoubleClickSelector.java   
@Override
protected IRegion findExtendedDoubleClickSelection(IDocument document, int offset) {
    IRegion match= super.findExtendedDoubleClickSelection(document, offset);
    if (match != null)
        return match;

    try {
        ITypedRegion region= TextUtilities.getPartition(document, fPartitioning, offset, true);
        if (offset == region.getOffset() + 1 || offset == region.getOffset() + region.getLength() - 1) {
            return getSelectedRegion(document, region);
        }
    } catch (BadLocationException e) {
        return null;
    }
    return null;
}
项目:bts    文件:CompoundMultiLineTerminalsEditStrategy.java   
@Override
protected void internalCustomizeDocumentCommand(IDocument document, DocumentCommand command)
        throws BadLocationException {
    if (command.length != 0)
        return;
    String[] lineDelimiters = document.getLegalLineDelimiters();
    int delimiterIndex = TextUtilities.startsWith(lineDelimiters, command.text);
    if (delimiterIndex != -1) {
        MultiLineTerminalsEditStrategy bestStrategy = null;
        IRegion bestStart = null;
        for(MultiLineTerminalsEditStrategy strategy: strategies) {
            IRegion candidate = strategy.findStartTerminal(document, command.offset);
            if (candidate != null) {
                if (bestStart == null || bestStart.getOffset() < candidate.getOffset()) {
                    bestStrategy = strategy;
                    bestStart = candidate;
                }
            }
        }
        if (bestStrategy != null) {
            bestStrategy.internalCustomizeDocumentCommand(document, command);
        }
    }
}
项目:che    文件:JavaDocContext.java   
@Override
public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
  TemplateTranslator translator = new TemplateTranslator();
  TemplateBuffer buffer = translator.translate(template);

  getContextType().resolve(buffer, this);

  //        IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
  boolean useCodeFormatter =
      true; // prefs.getBoolean(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER);

  IJavaProject project = getJavaProject();
  JavaFormatter formatter =
      new JavaFormatter(
          TextUtilities.getDefaultLineDelimiter(getDocument()),
          getIndentation(),
          useCodeFormatter,
          project);
  formatter.format(buffer, this);

  return buffer;
}
项目:che    文件:SourceProvider.java   
private String[] getBlocks(RangeMarker[] markers) throws BadLocationException {
  String[] result = new String[markers.length];
  for (int i = 0; i < markers.length; i++) {
    RangeMarker marker = markers[i];
    String content = fDocument.get(marker.getOffset(), marker.getLength());
    String lines[] = Strings.convertIntoLines(content);
    Strings.trimIndentation(lines, fTypeRoot.getJavaProject(), false);
    if (fMarkerMode == STATEMENT_MODE
        && lines.length == 2
        && isSingleControlStatementWithoutBlock()) {
      lines[1] = CodeFormatterUtil.createIndentString(1, fTypeRoot.getJavaProject()) + lines[1];
    }
    result[i] = Strings.concatenate(lines, TextUtilities.getDefaultLineDelimiter(fDocument));
  }
  return result;
}
项目:che    文件:IndentUtil.java   
/**
 * 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);
}
项目:che    文件:JavaMethodCompletionProposal.java   
/**
 * Appends everything up to the method name including the opening parenthesis.
 *
 * <p>In case of {@link org.eclipse.jdt.core.CompletionProposal#METHOD_REF_WITH_CASTED_RECEIVER}
 * it add cast.
 *
 * @param buffer the string buffer
 * @since 3.4
 */
protected void appendMethodNameReplacement(StringBuffer buffer) {
  if (fProposal.getKind() == CompletionProposal.METHOD_REF_WITH_CASTED_RECEIVER) {
    String coreCompletion = String.valueOf(fProposal.getCompletion());
    String lineDelimiter = TextUtilities.getDefaultLineDelimiter(getTextViewer().getDocument());
    String replacement =
        CodeFormatterUtil.format(
            CodeFormatter.K_EXPRESSION,
            coreCompletion,
            0,
            lineDelimiter,
            fInvocationContext.getProject());
    buffer.append(replacement.substring(0, replacement.lastIndexOf('.') + 1));
  }

  if (fProposal.getKind() != CompletionProposal.CONSTRUCTOR_INVOCATION)
    buffer.append(fProposal.getName());

  FormatterPrefs prefs = getFormatterPrefs();
  if (prefs.beforeOpeningParen) buffer.append(SPACE);
  buffer.append(LPAREN);
}
项目:che    文件:JavadocTagsSubProcessor.java   
@Override
protected void addEdits(IDocument document, TextEdit rootEdit) throws CoreException {
  try {
    String lineDelimiter = TextUtilities.getDefaultLineDelimiter(document);
    final IJavaProject project = getCompilationUnit().getJavaProject();
    IRegion region = document.getLineInformationOfOffset(fInsertPosition);

    String lineContent = document.get(region.getOffset(), region.getLength());
    String indentString = Strings.getIndentString(lineContent, project);
    String str = Strings.changeIndent(fComment, 0, project, indentString, lineDelimiter);
    InsertEdit edit = new InsertEdit(fInsertPosition, str);
    rootEdit.addChild(edit);
    if (fComment.charAt(fComment.length() - 1) != '\n') {
      rootEdit.addChild(new InsertEdit(fInsertPosition, lineDelimiter));
      rootEdit.addChild(new InsertEdit(fInsertPosition, indentString));
    }
  } catch (BadLocationException e) {
    throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
  }
}
项目:gwt-eclipse-plugin    文件:IndependentMultiPassContentFormatter.java   
/**
 * Records the text of partitions for which we have a slave formatting
 * strategy.
 */
private void recordSlavePartitionsText() {
  try {
    ITypedRegion[] partitions = TextUtilities.computePartitioning(
        tempDocument, partitioning, 0, tempDocument.getLength(), false);
    savedPartitionText = new String[partitions.length];
    for (int i = 0; i < savedPartitionText.length; i++) {
      if (!isSlaveContentType(partitions[i].getType())) {
        continue;
      }

      savedPartitionText[i] = tempDocument.get(partitions[i].getOffset(),
          partitions[i].getLength());
    }
  } catch (BadLocationException e) {
    // This will never happen, according to super.formatSlaves
  }
}
项目:gwt-eclipse-plugin    文件:IndependentMultiPassContentFormatter.java   
private void replaceSlavePartitionsWithDummyText() {
  try {
    ITypedRegion[] partitions = TextUtilities.computePartitioning(
        tempDocument, partitioning, 0, tempDocument.getLength(), false);
    for (int i = 0; i < partitions.length; i++) {
      if (!isSlaveContentType(partitions[i].getType())) {
        continue;
      }

      // Ideally, we'd like to use whitespace as the dummy text, but it may
      // cause the partition to be lost by the master formatter. Instead this
      // uses periods.
      tempDocument.replace(partitions[i].getOffset(),
          partitions[i].getLength(), StringUtilities.repeatCharacter('.',
              partitions[i].getLength()));
    }
  } catch (BadLocationException e) {
    // This should not happen according to super class
  }
}
项目:gwt-eclipse-plugin    文件:SseUtilities.java   
/**
 * Finds the partition containing the given offset.
 * 
 * @param document the document to search
 * @param offset the offset used to find a matching partition
 * @return the partition, or null
 */
public static ITypedRegion getPartition(IStructuredDocument document, int offset) {
  ITypedRegion[] partitions;
  try {
    partitions = TextUtilities.computePartitioning(document,
        IStructuredPartitioning.DEFAULT_STRUCTURED_PARTITIONING, 0,
        document.getLength(), true);
  } catch (BadLocationException e) {
    CorePluginLog.logError(e, "Unexpected bad location exception.");
    return null;
  }

  for (ITypedRegion partition : partitions) {
    if (partition.getOffset() <= offset
        && offset < partition.getOffset() + partition.getLength()) {
      return partition;
    }
  }

  return null;
}
项目:gwt-eclipse-plugin    文件:JsniParser.java   
public static ITypedRegion getEnclosingJsniRegion(ITextSelection selection,
    IDocument document) {
  try {
    ITypedRegion region = TextUtilities.getPartition(document,
        GWTPartitions.GWT_PARTITIONING, selection.getOffset(), false);

    if (region.getType().equals(GWTPartitions.JSNI_METHOD)) {
      int regionEnd = region.getOffset() + region.getLength();
      int selectionEnd = selection.getOffset() + selection.getLength();

      // JSNI region should entirely contain the selection
      if (region.getOffset() <= selection.getOffset()
          && regionEnd >= selectionEnd) {
        return region;
      }
    }
  } catch (BadLocationException e) {
    GWTPluginLog.logError(e);
  }

  return null;
}
项目:gwt-eclipse-plugin    文件:JsniFormattingUtil.java   
public static String[] getJsniMethods(IDocument document) {

    try {
      List<String> jsniMethods = new LinkedList<String>();
      ITypedRegion[] regions = TextUtilities.computePartitioning(document,
          GWTPartitions.GWT_PARTITIONING, 0, document.getLength(), false);

      // Format all JSNI blocks in the document
      for (ITypedRegion region : regions) {
        if (region.getType().equals(GWTPartitions.JSNI_METHOD)) {
          String jsni = document.get(region.getOffset(), region.getLength());
          jsniMethods.add(jsni);
        }
      }

      return jsniMethods.toArray(new String[0]);

    } catch (BadLocationException e) {
      GWTPluginLog.logError(e);
      return null;
    }
  }
项目:KaiZen-OpenAPI-Editor    文件:QuickFixer.java   
@Override
public IRegion processFix(IDocument document, IMarker marker) throws CoreException {
    int line = (int) marker.getAttribute(IMarker.LINE_NUMBER);
    try {
        String indent = getIndent(document, line);
        // getLineOffset() is zero-based, and imarkerLine is one-based.
        int endOfCurrLine = document.getLineInformation(line - 1).getOffset()
                + document.getLineInformation(line - 1).getLength();
        // should be fine for first and last lines in the doc as well
        String replacementText = indent + "type: object";
        String delim = TextUtilities.getDefaultLineDelimiter(document);
        document.replace(endOfCurrLine, 0, delim + replacementText);
        return new Region(endOfCurrLine + delim.length(), replacementText.length());
    } catch (BadLocationException e) {
        throw new CoreException(createStatus(e, "Cannot process the IMarker"));
    }
}
项目:APICloud-Studio    文件:ContentAssistant.java   
/**
 * Returns the code assist processor for the content type of the specified document position.
 * 
 * @param viewer
 *            the text viewer
 * @param offset
 *            a offset within the document
 * @return a content-assist processor or <code>null</code> if none exists
 * @since 3.0
 */
public IContentAssistProcessor getProcessor(ITextViewer viewer, int offset)
{
    try
    {

        IDocument document = viewer.getDocument();
        String type = TextUtilities.getContentType(document, getDocumentPartitioning(), offset, true);

        return getContentAssistProcessor(type);

    }
    catch (BadLocationException x)
    {
    }

    return null;
}
项目:APICloud-Studio    文件:ContentAssistant.java   
/**
 * Returns the code assist processor for the content type of the specified document position.
 * 
 * @param contentAssistSubjectControl
 *            the code assist subject control
 * @param offset
 *            a offset within the document
 * @return a content-assist processor or <code>null</code> if none exists
 * @since 3.0
 */
private IContentAssistProcessor getProcessor(IContentAssistSubjectControl contentAssistSubjectControl, int offset)
{
    try
    {

        IDocument document = contentAssistSubjectControl.getDocument();
        String type;
        if (document != null)
        {
            type = TextUtilities.getContentType(document, getDocumentPartitioning(), offset, true);
        }
        else
        {
            type = IDocument.DEFAULT_CONTENT_TYPE;
        }

        return getContentAssistProcessor(type);

    }
    catch (BadLocationException x)
    {
    }

    return null;
}
项目:Eclipse-Postfix-Code-Completion    文件:MoveInstanceMethodProcessor.java   
/**
 * Creates the method content of the moved method.
 *
 * @param document
 *            the document representing the source compilation unit
 * @param declaration
 *            the source method declaration
 * @param rewrite
 *            the ast rewrite to use
 * @return the string representing the moved method body
 * @throws BadLocationException
 *             if an offset into the document is invalid
 */
protected String createMethodContent(final IDocument document, final MethodDeclaration declaration, final ASTRewrite rewrite) throws BadLocationException {
    Assert.isNotNull(document);
    Assert.isNotNull(declaration);
    Assert.isNotNull(rewrite);
    final IRegion range= new Region(declaration.getStartPosition(), declaration.getLength());
    final RangeMarker marker= new RangeMarker(range.getOffset(), range.getLength());
    final IJavaProject project= fMethod.getJavaProject();
    final TextEdit[] edits= rewrite.rewriteAST(document, project.getOptions(true)).removeChildren();
    for (int index= 0; index < edits.length; index++)
        marker.addChild(edits[index]);
    final MultiTextEdit result= new MultiTextEdit();
    result.addChild(marker);
    final TextEditProcessor processor= new TextEditProcessor(document, new MultiTextEdit(0, document.getLength()), TextEdit.UPDATE_REGIONS);
    processor.getRoot().addChild(result);
    processor.performEdits();
    final IRegion region= document.getLineInformation(document.getLineOfOffset(marker.getOffset()));
    return Strings.changeIndent(document.get(marker.getOffset(), marker.getLength()), Strings.computeIndentUnits(document.get(region.getOffset(), region.getLength()), project), project, "", TextUtilities.getDefaultLineDelimiter(document)); //$NON-NLS-1$
}
项目:Eclipse-Postfix-Code-Completion    文件:JavaDocContext.java   
@Override
public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
    TemplateTranslator translator= new TemplateTranslator();
    TemplateBuffer buffer= translator.translate(template);

    getContextType().resolve(buffer, this);

    IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
    boolean useCodeFormatter= prefs.getBoolean(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER);

    IJavaProject project= getJavaProject();
    JavaFormatter formatter= new JavaFormatter(TextUtilities.getDefaultLineDelimiter(getDocument()), getIndentation(), useCodeFormatter, project);
    formatter.format(buffer, this);

    return buffer;
}
项目:Eclipse-Postfix-Code-Completion    文件:SpecificContentAssistAction.java   
/**
* Computes the partition type at the selection start and checks whether the proposal category
* has any computers for this partition.
*
* @param selection the selection
* @return <code>true</code> if there are any computers for the selection
*/
  private boolean isValidSelection(ISelection selection) {
    if (!(selection instanceof ITextSelection))
        return false;
    int offset= ((ITextSelection) selection).getOffset();

    IDocument document= getDocument();
    if (document == null)
        return false;

    String contentType;
    try {
       contentType= TextUtilities.getContentType(document, IJavaPartitions.JAVA_PARTITIONING, offset, true);
      } catch (BadLocationException x) {
        return false;
      }

      return fCategory.hasComputers(contentType);
  }
项目:Eclipse-Postfix-Code-Completion    文件:JavaMethodCompletionProposal.java   
/**
 * Appends everything up to the method name including
 * the opening parenthesis.
 * <p>
 * In case of {@link CompletionProposal#METHOD_REF_WITH_CASTED_RECEIVER}
 * it add cast.
 * </p>
 *
 * @param buffer the string buffer
 * @since 3.4
 */
protected void appendMethodNameReplacement(StringBuffer buffer) {
    if (fProposal.getKind() == CompletionProposal.METHOD_REF_WITH_CASTED_RECEIVER) {
        String coreCompletion= String.valueOf(fProposal.getCompletion());
        String lineDelimiter= TextUtilities.getDefaultLineDelimiter(getTextViewer().getDocument());
        String replacement= CodeFormatterUtil.format(CodeFormatter.K_EXPRESSION, coreCompletion, 0, lineDelimiter, fInvocationContext.getProject());
        buffer.append(replacement.substring(0, replacement.lastIndexOf('.') + 1));
    }

    if (fProposal.getKind() != CompletionProposal.CONSTRUCTOR_INVOCATION)
        buffer.append(fProposal.getName());

    FormatterPrefs prefs= getFormatterPrefs();
    if (prefs.beforeOpeningParen)
        buffer.append(SPACE);
    buffer.append(LPAREN);
}
项目:Eclipse-Postfix-Code-Completion    文件:TemplateCompletionProposalComputer.java   
@Override
protected TemplateEngine computeCompletionEngine(JavaContentAssistInvocationContext context) {
    try {
        String partition= TextUtilities.getContentType(context.getDocument(), IJavaPartitions.JAVA_PARTITIONING, context.getInvocationOffset(), true);
        if (partition.equals(IJavaPartitions.JAVA_DOC))
            return fJavadocTemplateEngine;
        else {
            CompletionContext coreContext= context.getCoreContext();
            if (coreContext != null) {
                int tokenLocation= coreContext.getTokenLocation();
                if ((tokenLocation & CompletionContext.TL_MEMBER_START) != 0) {
                    return fJavaMembersTemplateEngine;
                }
                if ((tokenLocation & CompletionContext.TL_STATEMENT_START) != 0) {
                    return fJavaStatementsTemplateEngine;
                }
            }
            return fJavaTemplateEngine;
        }
    } catch (BadLocationException x) {
        return null;
    }
}
项目:Eclipse-Postfix-Code-Completion    文件:PartitionDoubleClickSelector.java   
@Override
protected IRegion findExtendedDoubleClickSelection(IDocument document, int offset) {
    IRegion match= super.findExtendedDoubleClickSelection(document, offset);
    if (match != null)
        return match;

    try {
        ITypedRegion region= TextUtilities.getPartition(document, fPartitioning, offset, true);
        if (offset == region.getOffset() + fHitDelta || offset == region.getOffset() + region.getLength() - fHitDelta) {
            if (fLeftBorder == 0 && fRightBorder == 0)
                return region;
            if (fRightBorder == -1) {
                String delimiter= document.getLineDelimiter(document.getLineOfOffset(region.getOffset() + region.getLength() - 1));
                if (delimiter == null)
                    fRightBorder= 0;
                else
                    fRightBorder= delimiter.length();
            }
            return new Region(region.getOffset() + fLeftBorder, region.getLength() - fLeftBorder - fRightBorder);
        }
    } catch (BadLocationException e) {
        return null;
    }
    return null;
}
项目:Eclipse-Postfix-Code-Completion    文件:JavaDocAutoIndentStrategy.java   
private String createMethodTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, IMethod method)
    throws CoreException, BadLocationException
{
    IRegion partition= TextUtilities.getPartition(document, fPartitioning, command.offset, false);
    IMethod inheritedMethod= getInheritedMethod(method);
    String comment= CodeGeneration.getMethodComment(method, inheritedMethod, lineDelimiter);
    if (comment != null) {
        comment= comment.trim();
        boolean javadocComment= comment.startsWith("/**"); //$NON-NLS-1$
        if (!isFirstComment(document, command, method, javadocComment))
            return null;
        boolean isJavaDoc= partition.getLength() >= 3 && document.get(partition.getOffset(), 3).equals("/**"); //$NON-NLS-1$
        if (javadocComment == isJavaDoc) {
            return prepareTemplateComment(comment, indentation, method.getJavaProject(), lineDelimiter);
        }
    }
    return null;
}
项目:Eclipse-Postfix-Code-Completion    文件:JavaDocAutoIndentStrategy.java   
@Override
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {

    if (!isSmartMode())
        return;

    if (command.text != null) {
        if (command.length == 0) {
            String[] lineDelimiters= document.getLegalLineDelimiters();
            int index= TextUtilities.endsWith(lineDelimiters, command.text);
            if (index > -1) {
                // ends with line delimiter
                if (lineDelimiters[index].equals(command.text))
                    // just the line delimiter
                    indentAfterNewLine(document, command);
                return;
            }
        }

        if (command.text.equals("/")) { //$NON-NLS-1$
            indentAfterCommentEnd(document, command);
            return;
        }
    }
}