當前位置: 首頁>>代碼示例>>Java>>正文


Java Document.get方法代碼示例

本文整理匯總了Java中org.eclipse.jface.text.Document.get方法的典型用法代碼示例。如果您正苦於以下問題:Java Document.get方法的具體用法?Java Document.get怎麽用?Java Document.get使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.eclipse.jface.text.Document的用法示例。


在下文中一共展示了Document.get方法的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: visit

import org.eclipse.jface.text.Document; //導入方法依賴的package包/類
@Override
public boolean visit(CopyTargetEdit edit) {
    try {
        org.eclipse.lsp4j.TextEdit te = new org.eclipse.lsp4j.TextEdit();
        te.setRange(JDTUtils.toRange(compilationUnit, edit.getOffset(), edit.getLength()));

        Document doc = new Document(compilationUnit.getSource());
        edit.apply(doc, TextEdit.UPDATE_REGIONS);
        String content = doc.get(edit.getSourceEdit().getOffset(), edit.getSourceEdit().getLength());
        te.setNewText(content);
        converted.add(te);
    } catch (MalformedTreeException | BadLocationException | CoreException e) {
        JavaLanguageServerPlugin.logException("Error converting TextEdits", e);
    }
    return false; // do not visit children
}
 
開發者ID:eclipse,項目名稱:eclipse.jdt.ls,代碼行數:17,代碼來源:TextEditConverter.java

示例2: apply

import org.eclipse.jface.text.Document; //導入方法依賴的package包/類
public static String apply(Document doc, Collection<? extends TextEdit> edits) throws BadLocationException {
    Assert.isNotNull(doc);
    Assert.isNotNull(edits);
    List<TextEdit> sortedEdits = new ArrayList<>(edits);
    sortByLastEdit(sortedEdits);
    String text = doc.get();
    for (int i = sortedEdits.size() - 1; i >= 0; i--) {
        TextEdit te = sortedEdits.get(i);
        Range r = te.getRange();
        if (r != null && r.getStart() != null && r.getEnd() != null) {
            int start = getOffset(doc, r.getStart());
            int end = getOffset(doc, r.getEnd());
            text = text.substring(0, start)
                    + te.getNewText()
                    + text.substring(end, text.length());
        }
    }
    return text;
}
 
開發者ID:eclipse,項目名稱:eclipse.jdt.ls,代碼行數:20,代碼來源:TextEditUtil.java

示例3: format

import org.eclipse.jface.text.Document; //導入方法依賴的package包/類
/**
 * Old API. Consider to use format2 (TextEdit)
 *
 * @param kind Use to specify the kind of the code snippet to format. It can be any of the kind
 *     constants defined in {@link org.eclipse.jdt.core.formatter.CodeFormatter}
 * @param source The source to format
 * @param indentationLevel The initial indentation level, used to shift left/right the entire
 *     source fragment. An initial indentation level of zero or below has no effect.
 * @param lineSeparator The line separator to use in formatted source, if set to <code>null</code>
 *     , then the platform default one will be used.
 * @param options The options map to use for formatting with the default code formatter.
 *     Recognized options are documented on {@link
 *     org.eclipse.jdt.core.JavaCore#getDefaultOptions()}. If set to <code>null</code>, then use
 *     the current settings from {@link org.eclipse.jdt.core.JavaCore#getOptions()}.
 * @return the formatted source string
 */
public static String format(
    int kind,
    String source,
    int indentationLevel,
    String lineSeparator,
    Map<String, String> options) {
  TextEdit edit = format2(kind, source, indentationLevel, lineSeparator, options);
  if (edit == null) {
    return source;
  } else {
    Document document = new Document(source);
    try {
      edit.apply(document, TextEdit.NONE);
    } catch (BadLocationException e) {
      JavaPlugin.log(e); // bug in the formatter
      Assert.isTrue(
          false,
          "Formatter created edits with wrong positions: " + e.getMessage()); // $NON-NLS-1$
    }
    return document.get();
  }
}
 
開發者ID:eclipse,項目名稱:che,代碼行數:39,代碼來源:CodeFormatterUtil.java

示例4: reformatJavaSourceAsString

import org.eclipse.jface.text.Document; //導入方法依賴的package包/類
/**
 * Given a String containing the text of a Java source file, return the same
 * Java source, but reformatted by the Eclipse auto-format code, with the
 * user's current Java preferences.
 */
public static String reformatJavaSourceAsString(String source) {
  TextEdit reformatTextEdit = CodeFormatterUtil.format2(
      CodeFormatter.K_COMPILATION_UNIT, source, 0, (String) null,
      JavaCore.getOptions());
  if (reformatTextEdit != null) {
    Document document = new Document(source);
    try {
      reformatTextEdit.apply(document, TextEdit.NONE);
      source = document.get();
    } catch (BadLocationException ble) {
      CorePluginLog.logError(ble);
    }
  }
  return source;
}
 
開發者ID:gwt-plugins,項目名稱:gwt-eclipse-plugin,代碼行數:21,代碼來源:ProjectResources.java

示例5: formatJava

import org.eclipse.jface.text.Document; //導入方法依賴的package包/類
private String formatJava(IType type) throws JavaModelException {
  String source = type.getCompilationUnit().getSource();
  CodeFormatter formatter = ToolFactory.createCodeFormatter(type.getJavaProject().getOptions(true));
  TextEdit formatEdit = formatter.format(CodeFormatterFlags.getFlagsForCompilationUnitFormat(), source, 0,
      source.length(), 0, lineDelimiter);
  if (formatEdit == null) {
    CorePluginLog.logError("Could not format source for " + type.getCompilationUnit().getElementName());
    return source;
  }

  Document document = new Document(source);
  try {
    formatEdit.apply(document);
    source = document.get();
  } catch (BadLocationException e) {
    CorePluginLog.logError(e);
  }

  source = Strings.trimLeadingTabsAndSpaces(source);
  return source;
}
 
開發者ID:gwt-plugins,項目名稱:gwt-eclipse-plugin,代碼行數:22,代碼來源:TypeCreator.java

示例6: asFormattedString

import org.eclipse.jface.text.Document; //導入方法依賴的package包/類
public static String asFormattedString(ASTNode node, int indent, String lineDelim, Map<String, String> options) {
    String unformatted= asString(node);
    TextEdit edit= CodeFormatterUtil.format2(node, unformatted, indent, lineDelim, options);
    if (edit != null) {
        Document document= new Document(unformatted);
        try {
            edit.apply(document, TextEdit.NONE);
        } catch (BadLocationException e) {
            // bug in the formatter
            JavaManipulationPlugin.log(e);
        }
        return document.get();
    }
    return unformatted; // unknown node
}
 
開發者ID:eclipse,項目名稱:eclipse.jdt.ls,代碼行數:16,代碼來源:ASTNodes.java

示例7: getCurrentIndent

import org.eclipse.jface.text.Document; //導入方法依賴的package包/類
/**
 * 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 asterisk 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(Document 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(LINE_COMMENT))
        to += 2;

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

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

    return document.get(from, to - from);
}
 
開發者ID:angelozerr,項目名稱:typescript.java,代碼行數:38,代碼來源:TypeScriptAutoIndentStrategy.java

示例8: loadTransliteration

import org.eclipse.jface.text.Document; //導入方法依賴的package包/類
private void loadTransliteration(BTSLemmaEntry lemma) {
//		if (lemma == null)
//		{
//			if (embeddedEditor != null)
//			{
//				embeddedEditorModelAccess.updateModel("\r",
//						"", "\r");
////				embeddedEditor.getViewer().setDocument(null);
//			}
//			return;
//		}
        modelAnnotationMap = new HashMap<String, BTSModelAnnotation>();
        relatingObjectsAnnotationMap = new HashMap<EObject, List<BTSModelAnnotation>>();
        Document doc = new Document();
        AnnotationModel tempAnnotationModel = new AnnotationModel();
        lemmaAnnotationMap = new HashMap<String, List<Object>>();
        lemmaEditorController.transformToDocument(textContent, doc, tempAnnotationModel, relatingObjects, relatingObjectsMap, lemmaAnnotationMap);

        String textString = doc.get();
        // take care of empty input
        if (textString.length() == 0)
        {
            textString = "§§";
        }
        embeddedEditorModelAccess.updateModel("\r",
                textString, "\r");
        annotationModel = embeddedEditor.getViewer().getAnnotationModel();

        loadAnnotations2Editor(annotationModel, tempAnnotationModel);

        processLemmaAnnotions(lemmaAnnotationMap);
    }
 
開發者ID:cplutte,項目名稱:bts,代碼行數:33,代碼來源:EgyLemmaEditorPart.java

示例9: asFormattedString

import org.eclipse.jface.text.Document; //導入方法依賴的package包/類
public static String asFormattedString(
    ASTNode node, int indent, String lineDelim, Map<String, String> options) {
  String unformatted = asString(node);
  TextEdit edit = CodeFormatterUtil.format2(node, unformatted, indent, lineDelim, options);
  if (edit != null) {
    Document document = new Document(unformatted);
    try {
      edit.apply(document, TextEdit.NONE);
    } catch (BadLocationException e) {
      JavaPlugin.log(e);
    }
    return document.get();
  }
  return unformatted; // unknown node
}
 
開發者ID:eclipse,項目名稱:che,代碼行數:16,代碼來源:ASTNodes.java

示例10: formatCode

import org.eclipse.jface.text.Document; //導入方法依賴的package包/類
@Override
public String formatCode(IType objectClass, String source) throws JavaModelException, BadLocationException {
    String lineDelim = getLineDelimiterUsed(objectClass);
    int indent = getUsedIndentation(objectClass) + 1;
    TextEdit textEdit = ToolFactory.createCodeFormatter(null).format(CodeFormatter.K_CLASS_BODY_DECLARATIONS,
            source, 0, source.length(), indent, lineDelim);
    if (textEdit == null) {
        return source;
    }
    Document document = new Document(source);
    textEdit.apply(document);
    return document.get();
}
 
開發者ID:maximeAudrain,項目名稱:jenerate,代碼行數:14,代碼來源:JavaCodeFormatterImpl.java

示例11: addGeneratedAnnotation

import org.eclipse.jface.text.Document; //導入方法依賴的package包/類
/**
 * @param file
 * @param info
 * @param monitor
 * @throws MalformedTreeException
 * @throws BadLocationException
 * @throws CoreException
 */
@SuppressWarnings("deprecation")
public static void addGeneratedAnnotation(IFile file, IFile graphFile, IProgressMonitor monitor)
        throws MalformedTreeException, BadLocationException, CoreException {
    ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(file);
    try {

        String source = compilationUnit.getSource();
        Document document = new Document(source);
        compilationUnit.becomeWorkingCopy(new SubProgressMonitor(monitor, 1));
        ASTParser parser = ASTParser.newParser(AST.JLS8);
        parser.setSource(compilationUnit);
        parser.setResolveBindings(true);
        CompilationUnit astRoot = (CompilationUnit) parser.createAST(new SubProgressMonitor(monitor, 1));
        astRoot.recordModifications();

        final ImportRewrite importRewrite = ImportRewrite.create(astRoot, true);
        importRewrite.addImport("javax.annotation.Generated");

        astRoot.accept(new ASTVisitor() {
            @SuppressWarnings("unchecked")
            @Override
            public boolean visit(TypeDeclaration node) {
                ASTNode copiedNode = null;
                // Add Generated annotation
                ClassExtension ce;
                try {
                    ce = new ClassExtension(false, false, false, false, false, false, "", "", null, false, false,
                            "", "", "", graphFile);
                    NormalAnnotation annotation = ce.getGeneratedClassAnnotation();
                    if (annotation != null) {
                        copiedNode = ASTNode.copySubtree(node.getAST(), annotation);
                        node.modifiers().add(0, copiedNode);
                    }
                } catch (JavaModelException e) {
                    ResourceManager.logException(e);
                }

                return super.visit(node);
            }
        });

        TextEdit rewrite = astRoot.rewrite(document, compilationUnit.getJavaProject().getOptions(true));
        rewrite.apply(document);

        TextEdit rewriteImports = importRewrite.rewriteImports(new SubProgressMonitor(monitor, 1));
        rewriteImports.apply(document);

        String newSource = document.get();
        compilationUnit.getBuffer().setContents(newSource);

        compilationUnit.reconcile(ICompilationUnit.NO_AST, false, null, new SubProgressMonitor(monitor, 1));
        compilationUnit.commitWorkingCopy(false, new SubProgressMonitor(monitor, 1));
    } finally {
        compilationUnit.discardWorkingCopy();
        monitor.done();
    }
    // WorkbenchFacade.JDTManager.reorganizeImport(compilationUnit);
}
 
開發者ID:gw4e,項目名稱:gw4e.project,代碼行數:67,代碼來源:JDTManager.java

示例12: updateReplacementString

import org.eclipse.jface.text.Document; //導入方法依賴的package包/類
public String updateReplacementString(IDocument document, int offset, ImportRewrite importRewrite,
        boolean snippetStringSupport)
                throws CoreException, BadLocationException {
    Document recoveredDocument= new Document();
    CompilationUnit unit= getRecoveredAST(document, offset, recoveredDocument);
    ImportRewriteContext context = new ContextSensitiveImportRewriteContext(unit, offset, importRewrite);

    ITypeBinding declaringType= null;
    ChildListPropertyDescriptor descriptor= null;
    ASTNode node= NodeFinder.perform(unit, offset, 1);
    node= ASTResolving.findParentType(node);
    String result = null;
    if (node instanceof AnonymousClassDeclaration) {
        declaringType= ((AnonymousClassDeclaration) node).resolveBinding();
        descriptor= AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY;
    } else if (node instanceof AbstractTypeDeclaration) {
        AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) node;
        descriptor= declaration.getBodyDeclarationsProperty();
        declaringType= declaration.resolveBinding();
    }
    if (declaringType != null) {
        ASTRewrite rewrite= ASTRewrite.create(unit.getAST());
        IMethodBinding methodToOverride= Bindings.findMethodInHierarchy(declaringType, fMethodName, fParamTypes);
        if (methodToOverride == null && declaringType.isInterface()) {
            methodToOverride= Bindings.findMethodInType(node.getAST().resolveWellKnownType("java.lang.Object"), fMethodName, fParamTypes); //$NON-NLS-1$
        }
        if (methodToOverride != null) {
            CodeGenerationSettings settings = PreferenceManager.getCodeGenerationSettings(fJavaProject.getProject());
            MethodDeclaration stub = StubUtility2.createImplementationStub(fCompilationUnit, rewrite, importRewrite,
                    context, methodToOverride, declaringType, settings, declaringType.isInterface(), declaringType,
                    snippetStringSupport);
            ListRewrite rewriter= rewrite.getListRewrite(node, descriptor);
            rewriter.insertFirst(stub, null);

            ITrackedNodePosition position= rewrite.track(stub);
            try {
                Map<String, String> options = fJavaProject.getOptions(true);

                rewrite.rewriteAST(recoveredDocument, options).apply(recoveredDocument);

                String generatedCode = recoveredDocument.get(position.getStartPosition(), position.getLength());

                String indentAt = getIndentAt(recoveredDocument, position.getStartPosition(), settings);
                int generatedIndent = IndentManipulation.measureIndentUnits(indentAt, settings.tabWidth,
                        settings.indentWidth);
                // Kinda fishy but empirical data shows Override needs to change indent by at
                // least 1
                generatedIndent = Math.max(1, generatedIndent);

                // Cancel generated code indent
                String delimiter = TextUtilities.getDefaultLineDelimiter(document);
                result = IndentManipulation.changeIndent(generatedCode, generatedIndent, settings.tabWidth,
                        settings.indentWidth, "", delimiter);

            } catch (MalformedTreeException | BadLocationException exception) {
                JavaLanguageServerPlugin.logException("Unable to compute override proposal", exception);
            }
        }
    }
    return result;
}
 
開發者ID:eclipse,項目名稱:eclipse.jdt.ls,代碼行數:62,代碼來源:OverrideCompletionProposal.java

示例13: format

import org.eclipse.jface.text.Document; //導入方法依賴的package包/類
public static TextEdit format(IDocument document, TypedPosition partition,
    Map<String, String> javaFormattingPrefs,
    Map<String, String> javaScriptFormattingPrefs, String original) {
  try {
    // Extract the JSNI block out of the document
    int offset = partition.getOffset();
    int length = partition.getLength();

    // Determine the line delimiter, indent string, and tab/indent widths
    String lineDelimiter = TextUtilities.getDefaultLineDelimiter(document);
    int tabWidth = IndentManipulation.getTabWidth(javaFormattingPrefs);
    int indentWidth = IndentManipulation.getIndentWidth(javaFormattingPrefs);

    // Get indentation level of the first line of the JSNI block (this should
    // be the line containing the JSNI method declaration)
    int methodDeclarationOffset = getMethodDeclarationOffset(document, offset);
    int jsniLine1 = document.getLineOfOffset(methodDeclarationOffset);
    int methodIndentLevel = getLineIndentLevel(document, jsniLine1, tabWidth,
        indentWidth);
    DefaultCodeFormatter defaultCodeFormatter = new DefaultCodeFormatter(
        javaFormattingPrefs);
    String indentLine = defaultCodeFormatter.createIndentationString(methodIndentLevel);

    // Extract the JSNI body out of the block and split it up by line
    String jsniSource = document.get(offset, length);
    String body = JsniParser.extractMethodBody(jsniSource);

    String formattedJs;

    // JSNI Java references mess up the JS formatter, so replace them
    // with place holder values
    JsniJavaRefReplacementResult replacementResults = replaceJsniJavaRefs(body);
    body = replacementResults.getJsni();

    TextEdit formatEdit = CodeFormatterUtil.format2(
        CodeFormatter.K_STATEMENTS, body, methodIndentLevel + 1,
        lineDelimiter, javaScriptFormattingPrefs);

    if (formatEdit != null) {

      body = restoreJsniJavaRefs(replacementResults);

      Document d = new Document(body);
      formatEdit.apply(d);

      formattedJs = d.get();

      if (!formattedJs.startsWith(lineDelimiter)) {
        formattedJs = lineDelimiter + formattedJs;
      }

      if (!formattedJs.endsWith(lineDelimiter)) {
        formattedJs = formattedJs + lineDelimiter;
      }

      formattedJs = formattedJs + indentLine;

      formattedJs = "/*-{" + formattedJs + "}-*/";

    } else {

      if (original == null) {
        return null;
      }

      formattedJs = original; // formatting failed, use the original string
    }

    return new ReplaceEdit(offset, length, formattedJs);

  } catch (Exception e) {
    GWTPluginLog.logError(e);
    return null;
  }
}
 
開發者ID:gwt-plugins,項目名稱:gwt-eclipse-plugin,代碼行數:76,代碼來源:JsniFormattingUtil.java


注:本文中的org.eclipse.jface.text.Document.get方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。