Java Code Examples for org.eclipse.jface.text.TextUtilities#computePartitioning()

The following examples show how to use org.eclipse.jface.text.TextUtilities#computePartitioning() . 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: IndependentMultiPassContentFormatter.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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
  }
}
 
Example 2
Source File: IndependentMultiPassContentFormatter.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
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
  }
}
 
Example 3
Source File: SseUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 4
Source File: JsniFormattingUtil.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
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;
    }
  }
 
Example 5
Source File: XtextSpellingReconcileStrategy.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected ITypedRegion[] computePartitioning(int offset, int length, String partitionType) {
	ITypedRegion[] result = new ITypedRegion[0];
	ITypedRegion[] allRegions = new ITypedRegion[0];
	try {
		allRegions = TextUtilities.computePartitioning(getDocument(), partitionType, offset, length, false);
	} catch (BadLocationException x) {
	}
	for (int i = 0; i < allRegions.length; i++) {
		if (shouldProcess(allRegions[i])) {
			result = concat(result, allRegions[i]);
		}

	}
	return result;
}
 
Example 6
Source File: JsniFormattingUtil.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a text edit that formats the given document according to the given
 * settings.
 * 
 * @param document The document to format.
 * @param javaFormattingPrefs The formatting preferences for Java, used to
 *          determine the method level indentation.
 * @param javaScriptFormattingPrefs The formatting preferences for JavaScript.
 *          See org.eclipse.wst.jsdt.internal.formatter
 *          .DefaultCodeFormatterOptions and
 *          org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants
 * @param originalJsniMethods The original jsni methods to use if the
 *          formatter fails to format the method. The original jsni Strings
 *          must be in the same order that the jsni methods occur in the
 *          document. This is to work around the Java formatter blasting the
 *          jsni tabbing for the format-on-save action. May be null.
 * @return A text edit that when applied to the document, will format the jsni
 *         methods.
 */
@SuppressWarnings({"unchecked", "rawtypes"})
public static TextEdit format(IDocument document, Map javaFormattingPrefs,
    Map javaScriptFormattingPrefs, String[] originalJsniMethods) {
  TextEdit combinedEdit = new MultiTextEdit();
  try {
    ITypedRegion[] regions = TextUtilities.computePartitioning(document,
        GWTPartitions.GWT_PARTITIONING, 0, document.getLength(), false);

    // Format all JSNI blocks in the document
    int i = 0;
    for (ITypedRegion region : regions) {
      if (region.getType().equals(GWTPartitions.JSNI_METHOD)) {
        String originalJsniMethod = null;
        if (originalJsniMethods != null && i < originalJsniMethods.length) {
          originalJsniMethod = originalJsniMethods[i];
        }
        TextEdit edit = format(document, new TypedPosition(region),
            javaFormattingPrefs, javaScriptFormattingPrefs,
            originalJsniMethod);
        if (edit != null) {
          combinedEdit.addChild(edit);
        }
        i++;
      }
    }
    return combinedEdit;

  } catch (BadLocationException e) {
    GWTPluginLog.logError(e);
    return null;
  }
}
 
Example 7
Source File: GWTSpellingEngine.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void check(IDocument document, IRegion[] regions,
    ISpellChecker checker, ISpellingProblemCollector collector,
    IProgressMonitor monitor) {
  try {
    List<IRegion> regionList = new ArrayList<IRegion>();
    for (int i = 0; i < regions.length; i++) {
      IRegion region = regions[i];
      // Compute the GWT partitioning so we can identify JSNI blocks
      ITypedRegion[] partitions = TextUtilities.computePartitioning(
          document, GWTPartitions.GWT_PARTITIONING, region.getOffset(),
          region.getLength(), false);
      // Spelling engine should ignore all JSNI block regions
      for (int j = 0; j < partitions.length; j++) {
        ITypedRegion partition = partitions[j];
        if (!GWTPartitions.JSNI_METHOD.equals(partition.getType())) {
          regionList.add(partition);
        }
      }
    }
    super.check(document,
        regionList.toArray(new IRegion[regionList.size()]), checker,
        collector, monitor);
  } catch (BadLocationException e) {
    // Ignore: the document has been changed in another thread and will be
    // checked again (our super class JavaSpellingEngine does the same).
  }
}
 
Example 8
Source File: CommonReconciler.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
protected ITypedRegion[] computePartitioning(int offset, int length)
{
	ITypedRegion[] regions = null;
	try
	{
		regions = TextUtilities
				.computePartitioning(getDocument(), getDocumentPartitioning(), offset, length, false);
	}
	catch (BadLocationException x)
	{
		regions = new TypedRegion[0];
	}
	return regions;
}
 
Example 9
Source File: MultiRegionSpellingReconcileStrategy.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Computes and returns the partitioning for the given region of the input document
 * of the reconciler's connected text viewer.
 *
 * @param offset the region offset
 * @param length the region length
 * @return the computed partitioning
 * @since 3.0
 */
private ITypedRegion[] computePartitioning(int offset, int length)
{
	ITypedRegion[] regions = null;
	try
	{
		regions = TextUtilities.computePartitioning(getDocument(), getDocumentPartitioning(), offset, length, false);
	} catch (BadLocationException x)
	{
		regions = new TypedRegion[0];
	}
	return regions;
}
 
Example 10
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);
  }
}
 
Example 11
Source File: EditorAction.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
public void run(IAction action) {
  if (targetEditor == null) {
    GWTPluginLog.logWarning("targetEditor is null");
    return;
  }

  IEditorInput editorInput = targetEditor.getEditorInput();
  IResource resource = (IResource) editorInput.getAdapter(IResource.class);
  ITextEditor javaEditor = (ITextEditor) targetEditor;
  ITextSelection sel = (ITextSelection) javaEditor.getSelectionProvider().getSelection();
  IDocument document = javaEditor.getDocumentProvider().getDocument(
      javaEditor.getEditorInput());

  IDocumentExtension3 document3 = (IDocumentExtension3) document;
  IDocumentPartitioner gwtPartitioner = document3.getDocumentPartitioner(GWTPartitions.GWT_PARTITIONING);

  String[] partitionings = document3.getPartitionings();
  String partitioning = (gwtPartitioner != null
      ? GWTPartitions.GWT_PARTITIONING : IJavaPartitions.JAVA_PARTITIONING);

  ITypedRegion[] types;
  try {
    types = TextUtilities.computePartitioning(document, partitioning,
        sel.getOffset(), sel.getLength(), false);
  } catch (BadLocationException e) {
    GWTPluginLog.logError(e);
    return;
  }

  String msg = "File: " + resource.getName();

  msg += "\nPartitionings: ";
  for (String part : partitionings) {
    msg += "\n" + part;
  }

  msg += "\n\nContent types: ";
  for (ITypedRegion type : types) {
    msg += "\n" + type.getType();
  }

  msg += "\n\nSelection range: (offset = " + sel.getOffset() + ", length = "
      + sel.getLength() + ")";

  MessageDialog.openInformation(targetEditor.getSite().getShell(),
      "Selection Info", msg);
}
 
Example 12
Source File: CommonPresentationReconciler.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
protected TextPresentation createPresentation(IRegion damage, IDocument document, IProgressMonitor monitor)
{
	try
	{
		int damageOffset = damage.getOffset();
		int damageLength = damage.getLength();
		if (damageOffset + damageLength > document.getLength())
		{
			int adjustedLength = document.getLength() - damageOffset;
			synchronized (this)
			{
				delayedRegions.remove(new Region(document.getLength(), damageLength - adjustedLength));
			}
			if (adjustedLength <= 0)
			{
				return null;
			}
			damageLength = adjustedLength;
		}
		TextPresentation presentation = new TextPresentation(damage, iterationPartitionLimit * 5);
		ITypedRegion[] partitioning = TextUtilities.computePartitioning(document, getDocumentPartitioning(),
				damageOffset, damageLength, false);
		if (partitioning.length == 0)
		{
			return presentation;
		}
		int limit = Math.min(iterationPartitionLimit, partitioning.length);
		int processingLength = partitioning[limit - 1].getOffset() + partitioning[limit - 1].getLength()
				- damageOffset;
		if (EclipseUtil.showSystemJobs())
		{
			monitor.subTask(MessageFormat.format(
					"processing region at offset {0}, length {1} in document of length {2}", damageOffset, //$NON-NLS-1$
					processingLength, document.getLength()));
		}

		for (int i = 0; i < limit; ++i)
		{
			ITypedRegion r = partitioning[i];
			IPresentationRepairer repairer = getRepairer(r.getType());
			if (monitor.isCanceled())
			{
				return null;
			}
			if (repairer != null)
			{
				repairer.createPresentation(presentation, r);
			}
			monitor.worked(r.getLength());
		}

		synchronized (this)
		{
			delayedRegions.remove(new Region(damageOffset, processingLength));
			if (limit < partitioning.length)
			{
				int offset = partitioning[limit].getOffset();
				delayedRegions.append(new Region(offset, damageOffset + damageLength - offset));
			}
		}
		return presentation;
	}
	catch (BadLocationException e)
	{
		return null;
	}
}
 
Example 13
Source File: JavaSourceViewer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns a segmentation of the line of the given document appropriate for
 * Bidi rendering.
 *
 * @param document the document
 * @param baseLevel the base level of the line
 * @param lineStart the offset of the line
 * @param lineText Text of the line to retrieve Bidi segments for
 * @return the line's Bidi segmentation
 * @throws BadLocationException in case lineOffset is not valid in document
 */
protected static int[] getBidiLineSegments(IDocument document, int baseLevel, int lineStart, String lineText) throws BadLocationException {

	if (lineText == null || document == null)
		return null;

	int lineLength= lineText.length();
	if (lineLength <= 2)
		return null;

	// Have ICU compute embedding levels. Consume these levels to reduce
	// the Bidi impact, by creating selective segments (preceding
	// character runs with a level mismatching the base level).
	// XXX: Alternatively, we could apply TextLayout. Pros would be full
	// synchronization with the underlying StyledText's (i.e. native) Bidi
	// implementation. Cons are performance penalty because of
	// unavailability of such methods as isLeftToRight and getLevels.

	Bidi bidi= new Bidi(lineText, baseLevel);
	if (bidi.isLeftToRight())
		// Bail out if this is not Bidi text.
		return null;

	IRegion line= document.getLineInformationOfOffset(lineStart);
	ITypedRegion[] linePartitioning= TextUtilities.computePartitioning(document, IJavaPartitions.JAVA_PARTITIONING, lineStart, line.getLength(), false);
	if (linePartitioning == null || linePartitioning.length < 1)
		return null;

	int segmentIndex= 1;
	int[] segments= new int[lineLength + 1];
	byte[] levels= bidi.getLevels();
	int nPartitions= linePartitioning.length;
	for (int partitionIndex= 0; partitionIndex < nPartitions; partitionIndex++) {

		ITypedRegion partition = linePartitioning[partitionIndex];
		int lineOffset= partition.getOffset() - lineStart;
		//Assert.isTrue(lineOffset >= 0 && lineOffset < lineLength);

		if (lineOffset > 0
				&& isMismatchingLevel(levels[lineOffset], baseLevel)
				&& isMismatchingLevel(levels[lineOffset - 1], baseLevel)) {
			// Indicate a Bidi segment at the partition start - provided
			// levels of both character at the current offset and its
			// preceding character mismatch the base paragraph level.
			// Partition end will be covered either by the start of the next
			// partition, a delimiter inside a next partition, or end of line.
			segments[segmentIndex++]= lineOffset;
		}
		if (IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())) {
			int partitionEnd= Math.min(lineLength, lineOffset + partition.getLength());
			while (++lineOffset < partitionEnd) {
				if (isMismatchingLevel(levels[lineOffset], baseLevel)
						&& String.valueOf(lineText.charAt(lineOffset)).matches(BIDI_DELIMITERS)) {
					// For default content types, indicate a segment before
					// a delimiting character with a mismatching embedding
					// level.
					segments[segmentIndex++]= lineOffset;
				}
			}
		}
	}
	if (segmentIndex <= 1)
		return null;

	segments[0]= 0;
	if (segments[segmentIndex - 1] != lineLength)
		segments[segmentIndex++]= lineLength;

	if (segmentIndex == segments.length)
		return segments;

	int[] newSegments= new int[segmentIndex];
	System.arraycopy(segments, 0, newSegments, 0, segmentIndex);
	return newSegments;
}
 
Example 14
Source File: ExpressionSyntaxColoringPage.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Color the text in the sample area according to the current preferences
 */
void applyStyles( )
{
	if ( fText == null || fText.isDisposed( ) )
		return;

	try
	{
		ITypedRegion[] regions = TextUtilities.computePartitioning( fDocument,
				IDocumentExtension3.DEFAULT_PARTITIONING,
				0,
				fDocument.getLength( ),
				true );
		if ( regions.length > 0 )
		{
			for ( int i = 0; i < regions.length; i++ )
			{
				ITypedRegion region = regions[i];
				String namedStyle = (String) fContextToStyleMap.get( region.getType( ) );
				if ( namedStyle == null )
					continue;
				TextAttribute attribute = getAttributeFor( namedStyle );
				if ( attribute == null )
					continue;
				int fontStyle = attribute.getStyle( )
						& ( SWT.ITALIC | SWT.BOLD | SWT.NORMAL );
				StyleRange style = new StyleRange( region.getOffset( ),
						region.getLength( ),
						attribute.getForeground( ),
						attribute.getBackground( ),
						fontStyle );
				style.strikeout = ( attribute.getStyle( ) & TextAttribute.STRIKETHROUGH ) != 0;
				style.underline = ( attribute.getStyle( ) & TextAttribute.UNDERLINE ) != 0;
				style.font = attribute.getFont( );
				fText.setStyleRange( style );
			}
		}
	}
	catch ( BadLocationException e )
	{
		ExceptionHandler.handle( e );
	}
}