Java Code Examples for org.eclipse.jface.text.IDocument#set()

The following examples show how to use org.eclipse.jface.text.IDocument#set() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ContentAssistProcessorTestBuilder.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected ContentAssistProcessorTestBuilder appendAndApplyProposal(ICompletionProposal proposal, ISourceViewer sourceViewer, String model, int position)
		throws Exception {
	IDocument document = sourceViewer.getDocument();
	int offset = position;
	if (model != null) {
		document.set(getModel() + model);
		offset += model.length();
	}
	if (proposal instanceof ICompletionProposalExtension2) {
		ICompletionProposalExtension2 proposalExtension2 = (ICompletionProposalExtension2) proposal;
		proposalExtension2.apply(sourceViewer, (char) 0, SWT.NONE, offset);	
	} else if (proposal instanceof ICompletionProposalExtension) {
		ICompletionProposalExtension proposalExtension = (ICompletionProposalExtension) proposal;
		proposalExtension.apply(document, (char) 0, offset);	
	} else  {
		proposal.apply(document);
	}
	return reset().append(document.get());
}
 
Example 2
Source File: EditTemplateDialog.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected void doTextWidgetChanged(Widget w) {
	if (w == fNameText) {
		fSuppressError= false;
		updateStatusAndButtons();
	} else if (w == fContextCombo) {
		String contextId= getContextId();
		fTemplateProcessor.setContextType(fContextTypeRegistry.getContextType(contextId));
		IDocument document= fPatternEditor.getDocument();
		String prefix= getPrefix();
		document.set(prefix + getPattern());
		fPatternEditor.setVisibleRegion(prefix.length(), document.getLength() - prefix.length());
		updateStatusAndButtons();
	} else if (w == fDescriptionText) {
		// nothing
	}
}
 
Example 3
Source File: JavaTemplatesPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void updatePatternViewer(Template template) {
	if (template == null) {
		getPatternViewer().getDocument().set(""); //$NON-NLS-1$
		return ;
	}
	String contextId= template.getContextTypeId();
	TemplateContextType type= getContextTypeRegistry().getContextType(contextId);
	fTemplateProcessor.setContextType(type);

	IDocument doc= getPatternViewer().getDocument();

	String start= null;
	if ("javadoc".equals(contextId)) { //$NON-NLS-1$
		start= "/**" + doc.getLegalLineDelimiters()[0]; //$NON-NLS-1$
	} else
		start= ""; //$NON-NLS-1$

	doc.set(start + template.getPattern());
	int startLen= start.length();
	getPatternViewer().setDocument(doc, startLen, doc.getLength() - startLen);
}
 
Example 4
Source File: JavaContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Evaluates a 'java' template in the context of a compilation unit
 *
 * @param template the template to be evaluated
 * @param compilationUnit the compilation unit in which to evaluate the template
 * @param position the position inside the compilation unit for which to evaluate the template
 * @return the evaluated template
 * @throws CoreException in case the template is of an unknown context type
 * @throws BadLocationException in case the position is invalid in the compilation unit
 * @throws TemplateException in case the evaluation fails
 */
public static String evaluateTemplate(Template template, ICompilationUnit compilationUnit, int position) throws CoreException, BadLocationException, TemplateException {

	TemplateContextType contextType= JavaPlugin.getDefault().getTemplateContextRegistry().getContextType(template.getContextTypeId());
	if (!(contextType instanceof CompilationUnitContextType))
		throw new CoreException(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, JavaTemplateMessages.JavaContext_error_message, null));

	IDocument document= new Document();
	if (compilationUnit != null && compilationUnit.exists())
		document.set(compilationUnit.getSource());

	CompilationUnitContext context= ((CompilationUnitContextType) contextType).createContext(document, position, 0, compilationUnit);
	context.setForceEvaluation(true);

	TemplateBuffer buffer= context.evaluate(template);
	if (buffer == null)
		return null;
	return buffer.getString();
}
 
Example 5
Source File: XdsSymfileDocumentProvider.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected boolean setDocumentContent(IDocument document,
		IEditorInput editorInput, String encoding) throws CoreException {
	String fileContents = null;

	File file = CoreEditorUtils.editorInputToFile(editorInput);
       if (file != null) {
           String filePath = file.getAbsolutePath();
           fileContents = CompileDriver.decodeSymFile(filePath);
       }
       else {
       	fileContents = Messages.SymFileEditor_CannotOpenFile;
       }
       document.set(fileContents);
	return true;
}
 
Example 6
Source File: ContentAssistProcessorTestBuilder.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected ContentAssistProcessorTestBuilder appendAndApplyProposal(ICompletionProposal proposal, ISourceViewer sourceViewer, String model, int position)
		throws Exception {
	IDocument document = sourceViewer.getDocument();
	int offset = position;
	if (model != null) {
		document.set(getModel() + model);
		offset += model.length();
	}
	if (proposal instanceof ICompletionProposalExtension2) {
		ICompletionProposalExtension2 proposalExtension2 = (ICompletionProposalExtension2) proposal;
		proposalExtension2.apply(sourceViewer, (char) 0, SWT.NONE, offset);	
	} else if (proposal instanceof ICompletionProposalExtension) {
		ICompletionProposalExtension proposalExtension = (ICompletionProposalExtension) proposal;
		proposalExtension.apply(document, (char) 0, offset);	
	} else  {
		proposal.apply(document);
	}
	return reset().append(document.get());
}
 
Example 7
Source File: PyFormatter.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
public static void formatAll(IDocument doc, IPyFormatStdProvider edit, boolean isOpenedFile, FormatStd formatStd,
        boolean throwSyntaxError, boolean allowChangingLines) throws SyntaxErrorException {
    String delimiter = PySelection.getDelimiter(doc);
    String formatted;
    try {
        formatted = formatStrAutopep8OrPyDev(edit != null ? edit.getPythonNature() : null, formatStd,
                throwSyntaxError, doc, delimiter, allowChangingLines);
    } catch (MisconfigurationException e) {
        Log.log(e);
        return;
    }

    String contents = doc.get();
    if (contents.equals(formatted)) {
        return; //it's the same: nothing to do.
    }
    if (!isOpenedFile) {
        doc.set(formatted);
    } else {
        //let's try to apply only the differences
        TextSelectionUtils.setOnlyDifferentCode(doc, contents, formatted);
    }
}
 
Example 8
Source File: EmbeddedEditorModelAccess.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public void updateModel(String prefix, String editablePart, String suffix) {
	IDocument document = this.viewer.getDocument();
	if (this.insertLineBreaks) {
		String delimiter = document.getLegalLineDelimiters()[0];
		if (document instanceof IDocumentExtension4) {
			delimiter = ((IDocumentExtension4) document).getDefaultLineDelimiter();
		}
		prefix = prefix + delimiter;
		suffix = delimiter + suffix;
	}
	String model = prefix + editablePart + suffix;
	this.viewer.setRedraw(false);
	this.viewer.getUndoManager().disconnect();
	document.set(model);
	this.viewer.setVisibleRegion(prefix.length(), editablePart.length());
	this.viewer.getUndoManager().connect(this.viewer);
	this.viewer.setRedraw(true);
}
 
Example 9
Source File: TestLSPIntegration.java    From aCute with Eclipse Public License 2.0 6 votes vote down vote up
private void workaroundOmniSharpIssue1088(IDocument document) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
	// Wait for document to be connected
	Method getDocumentListenersMethod = AbstractDocument.class.getDeclaredMethod("getDocumentListeners");
	getDocumentListenersMethod.setAccessible(true);
	new DisplayHelper() {
		@Override protected boolean condition() {
			try {
				return ((Collection<?>)getDocumentListenersMethod.invoke(document)).stream().anyMatch(o -> o.getClass().getName().contains("lsp4e"));
			} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				e.printStackTrace();
				return false;
			}
		}
	}.waitForCondition(Display.getDefault(), 5000);
	assertNotEquals("LS Document listener was not setup after 5s", Collections.emptyList(), getDocumentListenersMethod.invoke(document));
	// workaround https://github.com/OmniSharp/omnisharp-roslyn/issues/1445
	DisplayHelper.sleep(5000);
	// force fake modification for OmniSharp to wake up
	document.set(document.get().replace("Hello", "Kikoo"));
	DisplayHelper.sleep(500);
}
 
Example 10
Source File: EmbeddedEditorModelAccess.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public void updateModel(String model) {
	IDocument document = this.viewer.getDocument();
	this.viewer.setRedraw(false);
	this.viewer.getUndoManager().disconnect();
	document.set(model);
	this.viewer.resetVisibleRegion();
	this.viewer.getUndoManager().connect(this.viewer);
	this.viewer.setRedraw(true);
}
 
Example 11
Source File: PyCreateMethodTest.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
public void testPyCreateMethodInEmptyDoc() {
    PyCreateMethodOrField pyCreateMethod = new PyCreateMethodOrField();

    String source = "";
    IDocument document = new Document(source);
    ICoreTextSelection selection = new CoreTextSelection(document, 5, 0);
    RefactoringInfo info = new RefactoringInfo(document, selection, PY_27_ONLY_GRAMMAR_VERSION_PROVIDER);

    pyCreateMethod.execute(info, "MyMethod", new ArrayList<String>(), AbstractPyCreateAction.LOCATION_STRATEGY_END);

    assertContentsEqual("" +
            "def MyMethod():\n" +
            "    ${pass}${cursor}\n" +
            "\n" +
            "\n" +
            "", document.get());

    document.set("");
    pyCreateMethod.execute(info, "MyMethod2", new ArrayList<String>(),
            AbstractPyCreateAction.LOCATION_STRATEGY_BEFORE_CURRENT);

    assertContentsEqual("" +
            "def MyMethod2():\n" +
            "    ${pass}${cursor}\n" +
            "\n" +
            "\n" +
            "", document.get());
}
 
Example 12
Source File: ScriptEditor.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public void setScript( String script )
{
	try
	{
		IDocumentProvider provider = getDocumentProvider( );

		if ( provider != null )
		{
			IDocument document = provider.getDocument( getEditorInput( ) );

			if ( document != null )
			{
				document.set( script == null ? "" : script ); //$NON-NLS-1$
				return;
			}
		}
		input = createScriptInput( script );
	}
	finally
	{
		ISourceViewer viewer = getSourceViewer( );

		if ( viewer instanceof SourceViewer )
		{
			IUndoManager undoManager = ( (SourceViewer) viewer ).getUndoManager( );

			if ( undoManager != null )
			{
				undoManager.reset( );
			}
		}
	}
}
 
Example 13
Source File: MultiPageEditor.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Update source from model.
 */
public void updateSourceFromModel() {
  sourceTextEditor.setIgnoreTextEvent(true);
  IDocument doc = sourceTextEditor.getDocumentProvider().getDocument(
          sourceTextEditor.getEditorInput());
  doc.set(prettyPrintModel());
  sourceTextEditor.setIgnoreTextEvent(false);
}
 
Example 14
Source File: XSPPropBeanLoader.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
public void setValue(Object instance, IAttribute attribute, String value, DataChangeNotifier dataChangeNotifier) throws NodeException {
    super.setValue(instance, attribute, value, dataChangeNotifier);
    modList.put(attribute.getName(), value);
    IDocument pfeDoc = pfe.getDocumentProvider().getDocument(fei);
    String docContents = pfeDoc.get();
    
    String keyName = appProps.keyForAttr(attribute.getName());
    docContents = XSPPropertiesUtils.instance().setPropertiesAsString(docContents, keyName, value, jProps);

    pfeDoc.set(docContents);
}
 
Example 15
Source File: EmacsPlusConsole.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Clear console content.
 */
public void clear() {
	setName(WI_CONSOLE);
	removeBackground();
	setKeyHandler(null);
	if (!pre33) {
		clearConsole();	
	}
	IDocument document = getDocument();
	if (document != null) {
		document.set(EmacsPlusUtils.EMPTY_STR);
	}
	getWidget();
}
 
Example 16
Source File: DecoratedScriptEditor.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public void setScript( String script )
{
	try
	{
		IDocumentProvider provider = getDocumentProvider( );

		if ( provider != null )
		{
			IDocument document = provider.getDocument( getEditorInput( ) );

			if ( document != null )
			{
				document.set( script == null ? "" : script ); //$NON-NLS-1$
				return;
			}
		}
		input = createScriptInput( script );
	}
	finally
	{
		ISourceViewer viewer = getSourceViewer( );

		if ( viewer instanceof SourceViewer )
		{
			IUndoManager undoManager = ( (SourceViewer) viewer ).getUndoManager( );

			if ( undoManager != null )
			{
				undoManager.reset( );
			}
		}
	}
}
 
Example 17
Source File: ClassFileDocumentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected boolean setDocumentContent(IDocument document, IEditorInput editorInput, String encoding) throws CoreException {
	if (editorInput instanceof IClassFileEditorInput) {
		IClassFile classFile= ((IClassFileEditorInput) editorInput).getClassFile();
		String source= classFile.getSource();
		if (source == null)
			source= ""; //$NON-NLS-1$
		document.set(source);
		return true;
	}
	return super.setDocumentContent(document, editorInput, encoding);
}
 
Example 18
Source File: SourceEditor.java    From textuml with Eclipse Public License 1.0 5 votes vote down vote up
private void doFormat() {
    ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
    IDocument document = getWorkingCopy().getDocument();
    String toFormat = document.get();
    String formatted = new TextUMLCompiler().format(toFormat);
    document.set(formatted);
    getSelectionProvider().setSelection(selection);
}
 
Example 19
Source File: JavaTemplatePreferencePage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void updateViewerInput() {
	IStructuredSelection selection= (IStructuredSelection) getTableViewer().getSelection();
	SourceViewer viewer= getViewer();

	if (selection.size() == 1 && selection.getFirstElement() instanceof TemplatePersistenceData) {
		TemplatePersistenceData data= (TemplatePersistenceData) selection.getFirstElement();
		Template template= data.getTemplate();
		String contextId= template.getContextTypeId();
		TemplateContextType type= JavaPlugin.getDefault().getTemplateContextRegistry().getContextType(contextId);
		fTemplateProcessor.setContextType(type);

		IDocument doc= viewer.getDocument();

		String start= null;
		if ("javadoc".equals(contextId)) { //$NON-NLS-1$
			start= "/**" + doc.getLegalLineDelimiters()[0]; //$NON-NLS-1$
		} else
			start= ""; //$NON-NLS-1$

		doc.set(start + template.getPattern());
		int startLen= start.length();
		viewer.setDocument(doc, startLen, doc.getLength() - startLen);

	} else {
		viewer.getDocument().set(""); //$NON-NLS-1$
	}
}
 
Example 20
Source File: IndependentMultiPassContentFormatter.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected void formatSlaves(IFormattingContext context, IDocument document,
    int offset, int length) {
  try {
    if (masterFormatterHadError) {
      // Do not proceed if the master formatter had an error
      return;
    }

    // Revert any master changes of partitions for which we have a slave
    // formatting strategy
    try {
      ITypedRegion[] partitions = TextUtilities.computePartitioning(
          tempDocument, partitioning, 0, tempDocument.getLength(), false);
      if (partitions.length == savedPartitionText.length) {
        for (int i = 0; i < savedPartitionText.length; i++) {
          if (savedPartitionText[i] == null) {
            continue;
          }

          tempDocument.replace(partitions[i].getOffset(),
              partitions[i].getLength(), savedPartitionText[i]);

          if (partitions[i].getLength() != savedPartitionText[i].length()) {
            // Recompute partitions since our replacement affects subsequent
            // offsets
            partitions = TextUtilities.computePartitioning(tempDocument,
                partitioning, 0, tempDocument.getLength(), false);
          }
        }
      }
    } catch (BadLocationException e) {
      // This will never happen, according to super.formatSlaves
    }

    if (length > tempDocument.getLength()) {
      // Safeguard against the master formatter shortening the document
      length = tempDocument.getLength();
    }

    // Ensure the superclass works off the temp document
    setToTempDocument(context);
    super.formatSlaves(context, tempDocument, offset, length);

    String tempText = tempDocument.get();
    if (!tempText.equals(premasterDocumentText)) {
      if (!checkForNonwhitespaceChanges
          || StringUtilities.equalsIgnoreWhitespace(tempText,
          premasterDocumentText, true)) {
        // Replace the text since it is different than what we started the
        // with
        document.set(tempText);
      } else {
        CorePluginLog.logWarning("Not applying formatting since it would cause non-whitespace changes.");
      }
    }
  } finally {
    /*
     * This will always be called. The super.format method tries calling
     * formatMaster, and in a finally block calls formatSlaves. We try-finally
     * on entry into formatSlaves.
     */
    documentCloner.release(tempDocument);
  }
}