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

项目:gw4e.project    文件:InvalidAnnotationPathGeneratorMarkerResolution.java   
private void fix(IMarker marker, IProgressMonitor monitor) {
    MarkerResolutionGenerator.printAttributes (marker);
    try {
        String filepath  = (String) marker.getAttribute(BuildPolicyConfigurationException.JAVAFILENAME);
        int start = (int) marker.getAttribute(IMarker.CHAR_START);
        int end =  (int) marker.getAttribute(IMarker.CHAR_END);
        IFile ifile = (IFile) ResourceManager.toResource(new Path(filepath));
        ICompilationUnit cu = JavaCore.createCompilationUnitFrom(ifile);
        String source = cu.getBuffer().getContents();
        String part1 =  source.substring(0,start);
        String part2 =  source.substring(end);
        source = part1 + "value=\"" + resolutionMarkerDescription.getGenerator() + "\"" + part2;
        final Document document = new Document(source);
        cu.getBuffer().setContents(document.get());
        cu.save(monitor, false);
    } catch (Exception e) {
        ResourceManager.logException(e);
    }
}
项目:convertigo-eclipse    文件:ConnectorEditorPart.java   
/**
 * This method initializes compositeXml
 * 
 */
private void createCompositeXml() {
    compositeXml = new Composite(sashForm, SWT.NONE);
    compositeXml.setLayout(new FillLayout());

    xmlView = new StructuredTextViewer(compositeXml, null, null, false, SWT.H_SCROLL | SWT.V_SCROLL);
    xmlView.setEditable(false);

    colorManager = new ColorManager();
    xmlView.configure(new XMLConfiguration(colorManager));

    Document document = new Document(
            "Click on the XML generation button to view the XML document generated by Convertigo.");
    IDocumentPartitioner partitioner = new FastPartitioner(new XMLPartitionScanner(), new String[] {
            XMLPartitionScanner.XML_TAG, XMLPartitionScanner.XML_COMMENT, });
    partitioner.connect(document);
    document.setDocumentPartitioner(partitioner);
    xmlView.setDocument(document);
}
项目:convertigo-eclipse    文件:ConnectorEditorPart.java   
public void documentGenerated(EngineEvent engineEvent) {
    if (!checkEventSource(engineEvent))
        return;

    if (bDebug) {
        try {
            ConvertigoPlugin.getDefault().debugConsoleStream
                    .write("The XML document has been successfully generated.\n");
        } catch (IOException e) {
        }
    }
    lastGeneratedDocument = (org.w3c.dom.Document) engineEvent.getSource();
    final String strXML = XMLUtils.prettyPrintDOMWithEncoding(lastGeneratedDocument);
    getDisplay().asyncExec(new Runnable() {
        public void run() {
            xmlView.getDocument().set(strXML);
            editor.setDirty(false);
        }
    });
}
项目:convertigo-eclipse    文件:SequenceEditorPart.java   
/**
 * This method initializes compositeXml 
 *
 */
private void createCompositeXml() {
    compositeXml = new Composite(sashForm, SWT.NONE);
    compositeXml.setLayout(new FillLayout());

    xmlView = new StructuredTextViewer(compositeXml, null, null, false, SWT.H_SCROLL | SWT.V_SCROLL);
    xmlView.setEditable(false);

    colorManager = new ColorManager();
    xmlView.configure(new XMLConfiguration(colorManager));

    Document document = new Document("Click on the XML generation button to view the XML document generated by Convertigo.");
    IDocumentPartitioner partitioner =
        new FastPartitioner(
            new XMLPartitionScanner(),
            new String[] { 
                XMLPartitionScanner.XML_TAG,
                XMLPartitionScanner.XML_COMMENT,
            }
        );
    partitioner.connect(document);
    document.setDocumentPartitioner(partitioner);
    xmlView.setDocument(document);
}
项目:convertigo-eclipse    文件:SequenceEditorPart.java   
public void documentGenerated(EngineEvent engineEvent) {
    if (!checkEventSource(engineEvent))
        return;

       if (bDebug) {
        try {
            ConvertigoPlugin.getDefault().debugConsoleStream.write("The XML document has been successfully generated.\n");
        } catch (IOException e) {}
       }

    lastGeneratedDocument = (org.w3c.dom.Document) engineEvent.getSource();
    final String strXML = XMLUtils.prettyPrintDOMWithEncoding(lastGeneratedDocument);
    getDisplay().asyncExec(new Runnable() {
        public void run() {
            xmlView.getDocument().set(strXML);
            editor.setDirty(false);
        }
    });
}
项目:bayou    文件:Visitor.java   
/**
 * Performs global post-processing of synthesized code:
 * - Adds import declarations
 *
 * @param ast      the owner of the document
 * @param env      environment that was used for synthesis
 * @param document draft program document
 * @throws BadLocationException if an error occurred when rewriting document
 */
private void postprocessGlobal(AST ast, Environment env, Document document)
        throws BadLocationException {
    /* add imports */
    ASTRewrite rewriter = ASTRewrite.create(ast);
    ListRewrite lrw = rewriter.getListRewrite(cu, CompilationUnit.IMPORTS_PROPERTY);
    Set<Class> toImport = new HashSet<>(env.imports);
    toImport.addAll(sketch.exceptionsThrown()); // add all catch(...) types to imports
    for (Class cls : toImport) {
        while (cls.isArray())
            cls = cls.getComponentType();
        if (cls.isPrimitive() || cls.getPackage().getName().equals("java.lang"))
            continue;
        ImportDeclaration impDecl = cu.getAST().newImportDeclaration();
        String className = cls.getName().replaceAll("\\$", "\\.");
        impDecl.setName(cu.getAST().newName(className.split("\\.")));
        lrw.insertLast(impDecl, null);
    }
    rewriter.rewriteAST(document, null).apply(document);
}
项目:aws-sdk-java-v2    文件:JavaCodeFormatter.java   
public String apply(String contents) {
    final TextEdit edit = codeFormatter.format(
            CodeFormatter.K_COMPILATION_UNIT
            | CodeFormatter.F_INCLUDE_COMMENTS, contents, 0,
            contents.length(), 0, Constants.LF);

    if (edit == null) {
        // TODO log a fatal or warning here. Throwing an exception is causing the actual freemarker error to be lost
        return contents;
    }

    IDocument document = new Document(contents);

    try {
        edit.apply(document);
    } catch (Exception e) {
        throw new RuntimeException(
                "Failed to format the generated source code.", e);
    }

    return document.get();
}
项目:tm4e    文件:TMEditor.java   
public TMEditor(IGrammar grammar, ITokenProvider tokenProvider, String text) {
    shell = new Shell();
    viewer = new TextViewer(shell, SWT.NONE);
    document = new Document();
    viewer.setDocument(document);
    commands = new ArrayList<>();
    collector = new StyleRangesCollector();

    setAndExecute(text);

    reconciler = new TMPresentationReconciler();
    reconciler.addTMPresentationReconcilerListener(collector);
    reconciler.setGrammar(grammar);
    reconciler.setTokenProvider(tokenProvider);
    reconciler.install(viewer);

}
项目:meghanada-server    文件:JavaFormatter.java   
public static String formatEclipseStyle(final Properties prop, final String content) {
  final CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(prop);
  final IDocument document = new Document(content);
  try {
    final TextEdit textEdit =
        codeFormatter.format(
            CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS,
            content,
            0,
            content.length(),
            0,
            null);
    if (textEdit != null) {
      textEdit.apply(document);
    } else {
      return content;
    }
  } catch (final BadLocationException e) {
    return content;
  }

  return ensureCorrectNewLines(document.get());
}
项目:team-explorer-everywhere    文件:TFSItemReferenceProvider.java   
private void getWorkspaceItem(final IProgressMonitor monitor) throws Exception {
    final TFSRepository repository =
        TFSCommonUIClientPlugin.getDefault().getProductPlugin().getRepositoryManager().getDefaultRepository();

    final GetVersionedItemToTempLocationCommand cmd = new GetVersionedItemToTempLocationCommand(
        repository,
        editorFile.getLocation().toOSString(),
        new WorkspaceVersionSpec(repository.getWorkspace()));

    final IStatus status = cmd.run(monitor);
    if (status != null && status.isOK()) {
        FileInputStream in = null;
        try {
            in = new FileInputStream(cmd.getTempLocation());
            final byte[] contents = new byte[in.available()];
            in.read(contents);
            reference = new Document(new String(contents));
        } finally {
            in.close();
        }
    }
}
项目:http4e    文件:DocumentUtils.java   
public static IDocument createDocument1(){
   IDocument doc = new Document(){
      public String getDefaultLineDelimiter(){
         return String.valueOf(AssistConstants.LINE_DELIM_NL) /*super.getDefaultLineDelimiter()*/;
      }
   };
   IDocumentPartitioner partitioner = new DefaultPartitioner(
         new HPartitionScanner(), 
         new String[] {
             HPartitionScanner.COMMENT,
             HPartitionScanner.PROPERTY_VALUE});
   partitioner.connect(doc);
   doc.setDocumentPartitioner(partitioner);

   return doc;  
}
项目:http4e    文件:DocumentUtils.java   
public static IDocument createDocument2() {
    IDocument document = new Document();
    if( document != null) {
        IDocumentPartitioner partitioner = new XMLPartitioner(
                new XMLPartitionScanner(), new String[] {
                        XMLPartitionScanner.XML_START_TAG,
                        XMLPartitionScanner.XML_PI,
                        XMLPartitionScanner.XML_DOCTYPE,
                        XMLPartitionScanner.XML_END_TAG,
                        XMLPartitionScanner.XML_TEXT,
                        XMLPartitionScanner.XML_CDATA,
                        XMLPartitionScanner.XML_COMMENT });
        partitioner.connect(document);
        document.setDocumentPartitioner(partitioner);
    }
    return document;
}
项目:eclipse.jdt.ls    文件:TextEditConverter.java   
@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
}
项目:eclipse.jdt.ls    文件:TextEditConverter.java   
@Override
public boolean visit(MoveTargetEdit 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
}
项目:eclipse.jdt.ls    文件:OverrideCompletionProposal.java   
private CompilationUnit getRecoveredAST(IDocument document, int offset, Document recoveredDocument) {
    CompilationUnit ast = SharedASTProvider.getInstance().getAST(fCompilationUnit, null);
    if (ast != null) {
        recoveredDocument.set(document.get());
        return ast;
    }

    char[] content= document.get().toCharArray();

    // clear prefix to avoid compile errors
    int index= offset - 1;
    while (index >= 0 && Character.isJavaIdentifierPart(content[index])) {
        content[index]= ' ';
        index--;
    }

    recoveredDocument.set(new String(content));

    final ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
    parser.setResolveBindings(true);
    parser.setStatementsRecovery(true);
    parser.setSource(content);
    parser.setUnitName(fCompilationUnit.getElementName());
    parser.setProject(fCompilationUnit.getJavaProject());
    return (CompilationUnit) parser.createAST(new NullProgressMonitor());
}
项目:eclipse.jdt.ls    文件:SaveActionHandlerTest.java   
@Test
public void testWillSaveWaitUntil() throws Exception {

    URI srcUri = project.getFile("src/java/Foo4.java").getRawLocationURI();
    ICompilationUnit cu = JDTUtils.resolveCompilationUnit(srcUri);

    StringBuilder buf = new StringBuilder();
    buf.append("package java;\n");
    buf.append("\n");
    buf.append("public class Foo4 {\n");
    buf.append("}\n");

    WillSaveTextDocumentParams params = new WillSaveTextDocumentParams();
    TextDocumentIdentifier document = new TextDocumentIdentifier();
    document.setUri(srcUri.toString());
    params.setTextDocument(document);

    List<TextEdit> result = handler.willSaveWaitUntil(params, monitor);

    Document doc = new Document();
    doc.set(cu.getSource());
    assertEquals(TextEditUtil.apply(doc, result), buf.toString());
}
项目:eclipse.jdt.ls    文件:HoverHandlerTest.java   
@Test
public void testHoverThrowable() throws Exception {
    String uriString = ClassFileUtil.getURI(project, "java.lang.Exception");
    IClassFile classFile = JDTUtils.resolveClassFile(uriString);
    String contents = JavaLanguageServerPlugin.getContentProviderManager().getSource(classFile, monitor);
    IDocument document = new Document(contents);
    IRegion region = new FindReplaceDocumentAdapter(document).find(0, "Throwable", true, false, false, false);
    int offset = region.getOffset();
    int line = document.getLineOfOffset(offset);
    int character = offset - document.getLineOffset(line);
    TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uriString);
    Position position = new Position(line, character);
    TextDocumentPositionParams params = new TextDocumentPositionParams(textDocument, position);
    Hover hover = handler.hover(params, monitor);
    assertNotNull(hover);
    assertTrue("Unexpected hover ", !hover.getContents().isEmpty());
}
项目:eclipse.jdt.ls    文件:AbstractQuickFixTest.java   
private String evaluateCodeActionCommand(Command c)
        throws BadLocationException, JavaModelException {
    Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand());
    Assert.assertNotNull(c.getArguments());
    Assert.assertTrue(c.getArguments().get(0) instanceof WorkspaceEdit);
    WorkspaceEdit we = (WorkspaceEdit) c.getArguments().get(0);
    Iterator<Entry<String, List<TextEdit>>> editEntries = we.getChanges().entrySet().iterator();
    Entry<String, List<TextEdit>> entry = editEntries.next();
    assertNotNull("No edits generated", entry);
    assertEquals("More than one resource modified", false, editEntries.hasNext());

    ICompilationUnit cu = JDTUtils.resolveCompilationUnit(entry.getKey());
    assertNotNull("CU not found: " + entry.getKey(), cu);

    Document doc = new Document();
    doc.set(cu.getSource());

    return TextEditUtil.apply(doc, entry.getValue());
}
项目:eclipse.jdt.ls    文件:TextEditUtil.java   
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;
}
项目:Black    文件:io.java   
public void New(File newfile)// �½��ļ���ͳһ���
{
    if (black.getEditer() == null) {
        black.createTextArea(null);
        black.setCurrentEditFile(newfile);
        black.tv.setDocument(new Document());
        black.setFileIsSave(1);
        black.applySetting();
        save(newfile);
    } else {
        black.closeCurrentFile(true);
        black.setCurrentEditFile(newfile);
        black.createTextArea(null);
        black.tv.setDocument(new Document());
        black.setFileIsSave(1);
        black.applySetting();
        save(newfile);
    }
}
项目:mesfavoris    文件:JavaEditorUtils.java   
public static Integer getLineNumber(IMember member) throws JavaModelException {
    ITypeRoot typeRoot = member.getTypeRoot();
    IBuffer buffer = typeRoot.getBuffer();
    if (buffer == null) {
        return null;
    }
    Document document = new Document(buffer.getContents());

    int offset = 0;
    if (SourceRange.isAvailable(member.getNameRange())) {
        offset = member.getNameRange().getOffset();
    } else if (SourceRange.isAvailable(member.getSourceRange())) {
        offset = member.getSourceRange().getOffset();
    }
    try {
        return document.getLineOfOffset(offset);
    } catch (BadLocationException e) {
        return null;
    }
}
项目:tlaplus    文件:TLCModelLaunchDataProvider.java   
/**
   * Resets the values to defaults
   */
  protected void initialize()
  {
      isDone = false;
      isTLCStarted = false;
      errors = new Vector<TLCError>();
      lastDetectedError = null;
      model.removeMarkers(ModelHelper.TLC_MODEL_ERROR_MARKER_TLC);

      coverageInfo = new Vector<CoverageInformationItem>();
      progressInformation = new Vector<StateSpaceInformationItem>();
      startTime = 0;
      startTimestamp = Long.MIN_VALUE;
      finishTimestamp = Long.MIN_VALUE;
      tlcMode = "";
      lastCheckpointTimeStamp = Long.MIN_VALUE;
      coverageTimestamp = "";
      setCurrentStatus(NOT_RUNNING);
      setFingerprintCollisionProbability("");
      progressOutput = new Document(NO_OUTPUT_AVAILABLE);
      userOutput = new Document(NO_OUTPUT_AVAILABLE);
      constantExprEvalOutput = "";

final IDialogSettings dialogSettings = Activator.getDefault().getDialogSettings();
stateSortDirection = dialogSettings.getBoolean(STATESORTORDER);
  }
项目:tlaplus    文件:TLCModelLaunchDataProvider.java   
/**
    * Sets text to a document
    * @param document
    * @param message
    * @param append
    * @throws BadLocationException
    * Has to be run from non-UI thread
    */
public static synchronized void setDocumentText(final Document document, final String message,
        final boolean append) {

    UIHelper.runUIAsync(new Runnable() {
        public void run() {
            try {
                DocumentRewriteSession rewriteSession;
                if (append && !isDefaultLabel(document)) {
                    rewriteSession = document.startRewriteSession(DocumentRewriteSessionType.SEQUENTIAL);
                    // append to existing document (0 length is valid and means message is going to be appended)
                    document.replace(document.getLength(), 0, message + ((message.endsWith(CR)) ? EMPTY : CR));
                } else {
                    rewriteSession = document.startRewriteSession(DocumentRewriteSessionType.STRICTLY_SEQUENTIAL);
                    // replace of complete document
                    document.replace(0, document.getLength(), message + ((message.endsWith(CR)) ? EMPTY : CR));
                }
                document.stopRewriteSession(rewriteSession);
            } catch (BadLocationException ignored) {
            }
        }
    });
}
项目:tlaplus    文件:ResultPage.java   
/**
    * Gets the data provider for the current page
    */
   public void loadData() throws CoreException
   {

    TLCOutputSourceRegistry modelCheckSourceRegistry = TLCOutputSourceRegistry.getModelCheckSourceRegistry();
    TLCModelLaunchDataProvider provider = modelCheckSourceRegistry.getProvider(getModel());
    if (provider != null) {
        provider.setPresenter(this);
    } else {
        // no data provider
        reinit();
    }

    // constant expression
    expressionEvalInput.setDocument(new Document(getModel().getEvalExpression()));
}
项目:tlaplus    文件:ResultPage.java   
/**
 * Reinitialize the fields
 * has to be run in the UI thread
 */
private synchronized void reinit()
{
    // TLCUIActivator.getDefault().logDebug("Entering reinit()");
    disposeLock.lock();
    try {
        if (getPartControl().isDisposed()) {
            // Cannot access widgets past their disposal
            return;
        }
        this.startTimestampText.setText("");
        this.startTime = 0;
        this.finishTimestampText.setText("");
        this.tlcModeText.setText("");
        this.lastCheckpointTimeText.setText("");
        this.currentStatusText.setText(TLCModelLaunchDataProvider.NOT_RUNNING);
        this.errorStatusHyperLink.setText(TLCModelLaunchDataProvider.NO_ERRORS);
        this.coverage.setInput(new Vector<CoverageInformationItem>());
        this.stateSpace.setInput(new Vector<StateSpaceInformationItem>());
        this.progressOutput.setDocument(new Document(TLCModelLaunchDataProvider.NO_OUTPUT_AVAILABLE));
        this.userOutput.setDocument(new Document(TLCModelLaunchDataProvider.NO_OUTPUT_AVAILABLE));
    } finally {
        disposeLock.unlock();
    }
    // TLCUIActivator.getDefault().logDebug("Exiting reinit()");
}
项目:tlaplus    文件:Bug267Listener.java   
protected void initialize() {
    isDone = false;
    isTLCStarted = false;
    errors = new Vector<TLCError>();
    lastDetectedError = null;
    coverageInfo = new Vector<CoverageInformationItem>();
    progressInformation = new Vector<StateSpaceInformationItem>();
    startTime = 0;
    startTimestamp = Long.MIN_VALUE;
    finishTimestamp = Long.MIN_VALUE;
    lastCheckpointTimeStamp = Long.MIN_VALUE;
    coverageTimestamp = "";
    setCurrentStatus(NOT_RUNNING);
    setFingerprintCollisionProbability("");
    progressOutput = new Document(NO_OUTPUT_AVAILABLE);
    userOutput = new Document(NO_OUTPUT_AVAILABLE);
    constantExprEvalOutput = "";
}
项目:typescript.java    文件:TypeScriptTemplatePreferencePage.java   
protected SourceViewer createViewer(Composite parent) {
    IDocument document= new Document();
    JavaScriptTextTools tools= JSDTTypeScriptUIPlugin.getDefault().getJavaTextTools();
    tools.setupJavaDocumentPartitioner(document, IJavaScriptPartitions.JAVA_PARTITIONING);
    IPreferenceStore store= JSDTTypeScriptUIPlugin.getDefault().getCombinedPreferenceStore();
    SourceViewer viewer= new JavaSourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL, store);
    SimpleJavaSourceViewerConfiguration configuration= new SimpleJavaSourceViewerConfiguration(tools.getColorManager(), store, null, IJavaScriptPartitions.JAVA_PARTITIONING, false);
    viewer.configure(configuration);
    viewer.setEditable(false);
    viewer.setDocument(document);

    Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
    viewer.getTextWidget().setFont(font);
    new TypeScriptSourcePreviewerUpdater(viewer, configuration, store);

    Control control= viewer.getControl();
    GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL);
    control.setLayoutData(data);

    return viewer;
}
项目:typescript.java    文件:TypeScriptAutoIndentStrategy.java   
/**
 * Installs a java partitioner with <code>document</code>.
 *
 * @param document the document
 */
private static void installJavaStuff(Document document) {
    String[] types= new String[] {
                                  IJavaScriptPartitions.JAVA_DOC,
                                  IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT,
                                  IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT,
                                  IJavaScriptPartitions.JAVA_STRING,
                                  IJavaScriptPartitions.JAVASCRIPT_TEMPLATE_LITERAL,
                                  IJavaScriptPartitions.JAVA_CHARACTER,
                                  IJSXPartitions.JSX,
                                  IDocument.DEFAULT_CONTENT_TYPE
    };
    FastPartitioner partitioner= new FastPartitioner(new FastTypeScriptPartitionScanner(), types);
    partitioner.connect(document);
    document.setDocumentPartitioner(IJavaScriptPartitions.JAVA_PARTITIONING, partitioner);
}
项目:strutsclipse    文件:StrutsXmlCompletionProposalComputerTest.java   
@Test
public void testResultTagName() throws Exception {
    final String content = "<result name=\"\"></result>";
    IDocument document = new Document(content);

    final int invocationOffset = content.lastIndexOf("\"");

    CompletionProposalInvocationContext context = new CompletionProposalInvocationContext(
            new MockTextViewer(document), invocationOffset);

    List<ICompletionProposal> proposals = computer
            .computeCompletionProposals(context, null);

    Assert.assertNotNull(proposals);
    Assert.assertFalse(proposals.isEmpty());

    Assert.assertEquals(StrutsXmlConstants.DEFAULT_RESULT_NAMES.length,
            proposals.size());
}
项目:strutsclipse    文件:StrutsXmlCompletionProposalComputerTest.java   
@Test
public void testActionTagMethod() throws Exception {
    final String content = "<action method=\"\"></action>";
    IDocument document = new Document(content);

    final int invocationOffset = content.lastIndexOf("\"");

    CompletionProposalInvocationContext context = new CompletionProposalInvocationContext(
            new MockTextViewer(document), invocationOffset);

    List<ICompletionProposal> proposals = computer
            .computeCompletionProposals(context, null);

    Assert.assertNotNull(proposals);
    Assert.assertFalse(proposals.isEmpty());

    Assert.assertEquals(StrutsXmlConstants.DEFAULT_METHODS.length,
            proposals.size());
}
项目:JSFLibraryGenerator    文件:JavaFormatter.java   
private static String formatCode(String contents, Object codeFormatter) {
    if (codeFormatter instanceof CodeFormatter) {
        IDocument doc = new Document(contents);
        TextEdit edit = ((CodeFormatter) codeFormatter).format(CodeFormatter.K_COMPILATION_UNIT, doc.get(), 0,
                doc.get().length(), 0, null);
        if (edit != null) {
            try {
                edit.apply(doc);
                contents = doc.get();
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
    return contents;
}
项目:bpm-beans    文件:DecisionTableEditor.java   
private CTabItem createDMNtab()
{
  CTabItem dmnTab = new CTabItem(tabs, SWT.NONE);
  dmnTab.setText("DMN");
  // assign a XML or DMN icon
  TextViewer dmnViewer = new TextViewer(tabs, SWT.V_SCROLL);
  dmnViewer.setDocument(new Document());
  dmnTab.setControl(dmnViewer.getTextWidget());
  dmnTab.addListener(SWT.SELECTED, evt -> {
    dmnViewer.getDocument().set(toDMN(table.model));
  });

  tabs.addSelectionListener(new SelectionAdapter() {
    @Override
    public void widgetSelected(SelectionEvent e) {
      tabs.getSelection().notifyListeners(SWT.SELECTED, new Event());
    }
   });
  return dmnTab;
}
项目:strutsclipse    文件:StrutsXmlParserTest.java   
@Test
public void testGetConstantNameRegions() throws Exception {
    final String one = "one";
    final String content = "<constant name='"
            + one
            + "' value='' /><constant name='two' value='' /><constant name='three' value='' />";
    IDocument document = new Document(content);

    List<ElementRegion> constantNameRegions = strutsXmlParser
            .getConstantNameRegions(document);

    Assert.assertNotNull(constantNameRegions);
    Assert.assertEquals(3, constantNameRegions.size());
    Assert.assertNotNull(constantNameRegions.get(0));
    Assert.assertEquals(StrutsXmlConstants.NAME_ATTR, constantNameRegions
            .get(0).getName());
    Assert.assertEquals(one, constantNameRegions.get(0).getValue());
}
项目:che    文件:TextChange.java   
private PreviewAndRegion getPreviewDocument(
    TextEditBasedChangeGroup[] changes, IProgressMonitor pm) throws CoreException {
  IDocument document = new Document(getCurrentDocument(pm).get());
  boolean trackChanges = getKeepPreviewEdits();
  setKeepPreviewEdits(true);
  TextEditProcessor processor =
      changes == ALL_EDITS
          ? createTextEditProcessor(document, TextEdit.NONE, true)
          : createTextEditProcessor(document, TextEdit.NONE, changes);
  try {
    processor.performEdits();
    return new PreviewAndRegion(document, getNewRegion(changes));
  } catch (BadLocationException e) {
    throw Changes.asCoreException(e);
  } finally {
    setKeepPreviewEdits(trackChanges);
  }
}
项目:che    文件:PomReconciler.java   
private Problem createProblem(String pomContent, SAXParseException spe) {
  Problem problem = DtoFactory.newDto(Problem.class);
  problem.setError(true);
  problem.setMessage(spe.getMessage());
  if (pomContent != null) {
    int lineNumber = spe.getLineNumber();
    int columnNumber = spe.getColumnNumber();
    try {
      Document document = new Document(pomContent);
      int lineOffset = document.getLineOffset(lineNumber - 1);
      problem.setSourceStart(lineOffset + columnNumber - 1);
      problem.setSourceEnd(lineOffset + columnNumber);
    } catch (BadLocationException e) {
      LOG.error(e.getMessage(), e);
    }
  }
  return problem;
}
项目:gwt-eclipse-plugin    文件:ProjectResources.java   
/**
 * 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;
}
项目:gwt-eclipse-plugin    文件:TypeCreator.java   
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;
}
项目:gwt-eclipse-plugin    文件:GWTCodeFormatterApplication.java   
private InputStream transformXmlToProperties(File f) throws IOException, SAXException, ParserConfigurationException {

    StringBuilder sb = new StringBuilder((int) f.length());
    sb.append("#\n");
    org.w3c.dom.Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(f);
    NodeList nodes = xml.getElementsByTagName("setting");

    for (int i = 0; i < nodes.getLength(); i++) {
      Node n = nodes.item(i);
      String key = n.getAttributes().getNamedItem("id").getNodeValue();
      String value = n.getAttributes().getNamedItem("value").getNodeValue();
      sb.append(key);
      sb.append('=');
      sb.append(value);
      sb.append('\n');
    }

    // this copies the string builder twice...
    return new ByteArrayInputStream(sb.toString().getBytes());
  }
项目:strutsclipse    文件:StrutsXmlParserTest.java   
@Test
public void testGetActionRegion() throws Exception {
    final String actionName = "in3";
    final String content = "<package namespace=\"/\"><action name=\"in1\"></action><action name=\"in2\"></action></package>"
            + "<package><action name=\"not\"></action></package>"
            + "<package namespace=\"/\"><action name=\""
            + actionName
            + "\"></action></package>";
    IDocument document = new Document(content);
    Set<String> namespaces = new HashSet<String>();
    namespaces.add("/");
    IRegion actionRegion = strutsXmlParser.getActionRegion(document,
            namespaces, actionName);

    Assert.assertNotNull(actionRegion);
    Assert.assertEquals(content.indexOf(actionName),
            actionRegion.getOffset());
}
项目:strutsclipse    文件:StrutsXmlCompletionProposalComputerTest.java   
@Test
public void testResultTagType() throws Exception {
    final String content = "<result type=\"\"></result>";
    IDocument document = new Document(content);

    final int invocationOffset = content.lastIndexOf("\"");

    CompletionProposalInvocationContext context = new CompletionProposalInvocationContext(
            new MockTextViewer(document), invocationOffset);

    List<ICompletionProposal> proposals = computer
            .computeCompletionProposals(context, null);

    Assert.assertNotNull(proposals);
    Assert.assertFalse(proposals.isEmpty());

    Assert.assertEquals(StrutsXmlConstants.DEFAULT_RESULT_TYPES.length,
            proposals.size());
}