org.eclipse.jface.text.TypedPosition Java Examples

The following examples show how to use org.eclipse.jface.text.TypedPosition. 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: PartitionCodeReaderTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
public void testPartitionCodeReaderKeepingPositions() throws Exception {
    PartitionCodeReader reader = new PartitionCodeReader(IDocument.DEFAULT_CONTENT_TYPE);
    Document document = new Document("abcde");
    String category = setupDocument(document);

    document.addPosition(category, new TypedPosition(1, 1, "cat1")); //skip b
    document.addPosition(category, new TypedPosition(3, 1, "cat1")); //skip d

    reader.configureForwardReader(document, 3, document.getLength(), true);
    FastStringBuffer buf = new FastStringBuffer(document.getLength());
    readAll(reader, buf);
    assertEquals("e", buf.toString());

    reader.configureForwardReaderKeepingPositions(2, document.getLength());
    buf.clear();
    readAll(reader, buf);
    assertEquals("ce", buf.toString());

    reader.configureForwardReaderKeepingPositions(0, document.getLength());
    buf.clear();
    readAll(reader, buf);
    assertEquals("ace", buf.toString());
}
 
Example #2
Source File: PartitionCodeReader.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Note: this just gets the positions in the document. To cover for holes, use
 * StringUtils.sortAndMergePositions with the result of this call.
 */
public static Position[] getDocumentTypedPositions(IDocument document, String defaultContentType) {
    if (ALL_CONTENT_TYPES_AVAILABLE.equals(defaultContentType)) {
        //Consider the whole document
        return new Position[] { new TypedPosition(0, document.getLength(), defaultContentType) };
    }
    Position[] positions;
    try {
        IDocumentPartitionerExtension2 partitioner = (IDocumentPartitionerExtension2) document
                .getDocumentPartitioner();
        String[] managingPositionCategories = partitioner.getManagingPositionCategories();
        Assert.isTrue(managingPositionCategories.length == 1);
        positions = document.getPositions(managingPositionCategories[0]);
        if (positions == null) {
            positions = new Position[] { new TypedPosition(0, document.getLength(), defaultContentType) };
        }
    } catch (Exception e) {
        Log.log("Unable to get positions for: " + defaultContentType, e); //Shouldn't happen, but if it does, consider the whole doc.
        positions = new Position[] { new TypedPosition(0, document.getLength(), defaultContentType) };
    }
    return positions;
}
 
Example #3
Source File: PartitionCodeReader.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
private Position[] createPositions(IDocument document) throws BadPositionCategoryException {
    Position[] positions = getDocumentTypedPositions(document, contentType);
    List<TypedPosition> typedPositions = PartitionMerger.sortAndMergePositions(positions, document.getLength());
    int size = typedPositions.size();
    List<Position> list = new ArrayList<Position>(size);
    for (int i = 0; i < size; i++) {
        Position position = typedPositions.get(i);
        if (isPositionValid(position, contentType)) {
            list.add(position);
        }
    }

    if (!fForward) {
        Collections.reverse(list);
    }
    Position[] ret = list.toArray(new Position[list.size()]);
    return ret;
}
 
Example #4
Source File: InlinedCssFormattingStrategy.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected String adjustFormattedCssWhitespace(String formattedCssBlock,
    IDocument document, TypedPosition partition, CssExtractor extractor) {
  try {
    String cssLineSeparator = extractor.getStructuredDocument().getLineDelimiter();
    String xmlLineSeparator = ((IStructuredDocument) document).getLineDelimiter();
    // The formattedCssBlock starts at column 0, we need to indent it to fit
    // with the <ui:style>'s indentation
    formattedCssBlock = indentCssForXml(formattedCssBlock, document,
        partition, cssLineSeparator, xmlLineSeparator);
    return formattedCssBlock;
  } catch (BadLocationException e) {
    GWTPluginLog.logWarning(e, "Could not format CSS block.");
  }

  return null;
}
 
Example #5
Source File: EmacsPlusUtils.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Get all positions of the given position category
 * In sexp's these positions are typically skipped
 * 
 * @param doc
 * @param pos_names
 * @return the positions to exclude
 */
public static List<Position> getExclusions(IDocument doc, String[] pos_names) {
	List<Position> excludePositions = new LinkedList<Position>();
	String cat = getTypeCategory(doc);
	if (cat != null) {
		try {
			Position[] xpos = doc.getPositions(cat);
			for (int j = 0; j < xpos.length; j++) {
				if (xpos[j] instanceof TypedPosition) {

					for (int jj = 0; jj < pos_names.length; jj++) {
						if (((TypedPosition) xpos[j]).getType().contains(pos_names[jj])) {
							excludePositions.add(xpos[j]);
						}
					}
				}
			}
		} catch (BadPositionCategoryException e) {}
	}
	return excludePositions;
}
 
Example #6
Source File: CommonMultiPassContentFormatter.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Update the fomatting context to reflect to the script formatter that should be used with the given content-type.
 * 
 * @param context
 * @param region
 * @param lastContentType
 */
private void updateContex(IFormattingContext context, String contentType, int offset, int length)
{
	IScriptFormatterFactory factory = ScriptFormatterManager.getSelected(contentType);
	if (factory != null)
	{
		factory.setMainContentType(contentType);
		if (context != null)
		{
			context.setProperty(ScriptFormattingContextProperties.CONTEXT_FORMATTER_ID, factory.getId());
			context.setProperty(FormattingContextProperties.CONTEXT_PARTITION, new TypedPosition(offset, length,
					contentType));
			context.setProperty(ScriptFormattingContextProperties.CONTEXT_FORMATTER_CAN_CONSUME_INDENTATION,
					factory.canConsumePreviousIndent());
		}
	}
}
 
Example #7
Source File: NonRuleBasedDamagerRepairer.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @see IPresentationRepairer#createPresentation(TextPresentation, ITypedRegion)
 */
public void createPresentation(TextPresentation presentation, ITypedRegion region)
{
	wipeExistingScopes(region);
	synchronized (getLockObject(fDocument))
	{
		try
		{
			fDocument.addPositionCategory(ICommonConstants.SCOPE_CATEGORY);
			fDocument.addPosition(
					ICommonConstants.SCOPE_CATEGORY,
					new TypedPosition(region.getOffset(), region.getLength(), (String) fDefaultTextAttribute
							.getData()));
		}
		catch (Exception e)
		{
			IdeLog.logError(CommonEditorPlugin.getDefault(), e);
		}
	}

	addRange(presentation, region.getOffset(), region.getLength(), getTextAttribute(region));
}
 
Example #8
Source File: DocumentPartitioner.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * May be replaced or extended by subclasses.
 * </p>
 * 
 * @since 2.2
 */
@Override
public synchronized String getContentType(int offset) {
	checkInitialization();

	TypedPosition p = findClosestPosition(offset);
	if (p != null && p.includes(offset))
		return p.getType();

	return IDocument.DEFAULT_CONTENT_TYPE;
}
 
Example #9
Source File: LangPartitionScannerTest.java    From goclipse with Eclipse Public License 1.0 5 votes vote down vote up
protected void checkPositions(Position[] positions, String[] expectedPositions) {
	assertTrue(positions.length == expectedPositions.length);
	for (int i = 0; i < positions.length; i++) {
		TypedPosition position = downCast(positions[i], TypedPosition.class);
		assertTrue(position.getType() == expectedPositions[i]);
	}
}
 
Example #10
Source File: PartitionCodeReaderTest.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
public void testPartitionCodeReaderMarkBackwards2() throws Exception {
    PartitionCodeReader reader = new PartitionCodeReader(IDocument.DEFAULT_CONTENT_TYPE);
    Document document = new Document("abcde");
    String category = setupDocument(document);

    document.addPosition(category, new TypedPosition(0, 1, "cat1")); //skip a
    document.addPosition(category, new TypedPosition(2, 1, "cat1")); //skip c
    document.addPosition(category, new TypedPosition(4, 1, "cat1")); //skip e

    reader.configureBackwardReader(document, document.getLength());
    int mark = reader.getMark();
    assertEquals(reader.read(), 'd');

    int mark2 = reader.getMark();
    assertEquals(reader.read(), 'b');

    int mark3 = reader.getMark();
    assertEquals(reader.read(), -1);

    reader.setMark(mark);
    assertEquals(reader.read(), 'd');
    assertEquals(reader.read(), 'b');
    assertEquals(reader.read(), -1);

    reader.setMark(mark2);
    assertEquals(reader.read(), 'b');
    assertEquals(reader.read(), -1);

    reader.setMark(mark3);
    assertEquals(reader.read(), -1);
}
 
Example #11
Source File: PartitionCodeReaderTest.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
public void testPartitionCodeReaderMark2() throws Exception {
    PartitionCodeReader reader = new PartitionCodeReader(IDocument.DEFAULT_CONTENT_TYPE);
    Document document = new Document("abcde");
    String category = setupDocument(document);

    document.addPosition(category, new TypedPosition(0, 1, "cat1")); //skip a
    document.addPosition(category, new TypedPosition(2, 1, "cat1")); //skip c
    document.addPosition(category, new TypedPosition(4, 1, "cat1")); //skip e

    reader.configureForwardReader(document, 0, document.getLength());
    int mark = reader.getMark();
    assertEquals(reader.read(), 'b');

    int mark2 = reader.getMark();
    assertEquals(reader.read(), 'd');

    int mark3 = reader.getMark();
    assertEquals(reader.read(), -1);

    reader.setMark(mark);
    assertEquals(reader.read(), 'b');
    assertEquals(reader.read(), 'd');
    assertEquals(reader.read(), -1);

    reader.setMark(mark2);
    assertEquals(reader.read(), 'd');
    assertEquals(reader.read(), -1);

    reader.setMark(mark3);
    assertEquals(reader.read(), -1);
}
 
Example #12
Source File: PartitionCodeReaderTest.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
public void testPartitionCodeReaderUnread2() throws Exception {
    PartitionCodeReader reader = new PartitionCodeReader(IDocument.DEFAULT_CONTENT_TYPE);
    Document document = new Document("abcde");
    String category = setupDocument(document);

    document.addPosition(category, new TypedPosition(1, 1, "cat1")); //skip b
    document.addPosition(category, new TypedPosition(3, 1, "cat1")); //skip d

    reader.configureForwardReader(document, 0, document.getLength());
    FastStringBuffer buf = new FastStringBuffer(document.getLength());
    readAll(reader, buf);
    reader.unread(); //EOF
    reader.unread(); //e
    reader.unread(); //c
    readAll(reader, buf);
    reader.unread(); //EOF
    reader.unread(); //e
    reader.unread(); //c
    reader.unread(); //a
    readAll(reader, buf);
    reader.unread(); //EOF
    assertEquals(-1, reader.read());
    reader.unread(); //EOF
    reader.unread(); //e
    readAll(reader, buf);
    assertEquals("aceceacee", buf.toString());
}
 
Example #13
Source File: PartitionCodeReader.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isPositionValid(Position position, String contentType) {
    if (fSupportKeepPositions || (fForward && position.getOffset() + position.getLength() >= fOffset || !fForward
            && position.getOffset() <= fOffset)) {
        if (position instanceof TypedPosition) {
            TypedPosition typedPosition = (TypedPosition) position;
            if (contentType != null && !contentType.equals(ALL_CONTENT_TYPES_AVAILABLE)) {
                if (!contentType.equals(typedPosition.getType())) {
                    return false;
                }
            }
        }
        return true;
    }
    return false;
}
 
Example #14
Source File: FastPartitioner.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * May be replaced or extended by subclasses.
 * </p>
 */
@Override
public String getContentType(int offset) {
    checkInitialization();

    TypedPosition p = findClosestPosition(offset);
    if (p != null && p.includes(offset)) {
        return p.getType();
    }

    return IDocument.DEFAULT_CONTENT_TYPE;
}
 
Example #15
Source File: JavaFormattingStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void formatterStarts(final IFormattingContext context) {
	super.formatterStarts(context);

	fPartitions.addLast((TypedPosition) context.getProperty(FormattingContextProperties.CONTEXT_PARTITION));
	fDocuments.addLast((IDocument) context.getProperty(FormattingContextProperties.CONTEXT_MEDIUM));
}
 
Example #16
Source File: CompositePartitionScanner.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setPartialRange(IDocument document, int offset, int length, String contentType, int partitionOffset) {
	defaultTokenState = null;
	hasResume = false;
	resetRules(defaultPartitionScanner.getRules());
	resetRules(primaryPartitionScanner.getRules());
	currentPartitionScanner = defaultPartitionScanner;
	currentPartitionScanner.setLastToken(new Token(contentType));
	if (IDocument.DEFAULT_CONTENT_TYPE.equals(contentType) && partitioner != null) {
		TypedPosition partition = partitioner.findClosestPosition(offset);
		if (partition != null) {
			if (partition.overlapsWith(offset, length)) {
				partition = partitioner.findClosestPosition(offset - 1);
			}
		}
		if (partition != null) {
			String type = partition.getType();
			if (primaryPartitionScanner.hasContentType(type)) {
				currentPartitionScanner = primaryPartitionScanner;
			} else if (START_SWITCH_TAG.equals(type)) {
				hasSwitch = true;
			}
			currentPartitionScanner.setLastToken(new Token(type));
		}
	} else if (primaryPartitionScanner.hasContentType(contentType)) {
		currentPartitionScanner = primaryPartitionScanner;
	}
	super.setPartialRange(document, offset, length, contentType, partitionOffset);
}
 
Example #17
Source File: ScriptFormattingStrategy.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param context
 * @param document
 * @param partition
 * @param project
 * @param formatterId
 * @param isSlave
 * @param canConsumeIndentation
 * @param isSelection
 * @param selectedRegion
 *            - Should be valid when isSelection is true.
 */
public FormatJob(IFormattingContext context, IDocument document, TypedPosition partition, IProject project,
		String formatterId, Boolean isSlave, Boolean canConsumeIndentation, Boolean isSelection,
		IRegion selectedRegion)
{
	this.context = context;
	this.document = document;
	this.partition = partition;
	this.project = project;
	this.formatterId = formatterId;
	this.canConsumeIndentation = canConsumeIndentation;
	this.isSlave = (isSlave != null) ? isSlave : false;
	this.isSelection = (isSelection != null) ? isSelection : false;
	this.selectedRegion = selectedRegion;
}
 
Example #18
Source File: DocumentPartitioner.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private boolean isOpenSingleLineCommentPartition(TypedPosition position, int offset) throws BadLocationException {
	if (position.isDeleted()) {
		return false;
	}
	int endOffset = position.getOffset() + position.getLength();
	if (offset != endOffset) {
		return false;
	}
	if (!TerminalsTokenTypeToPartitionMapper.SL_COMMENT_PARTITION.equals(position.getType())) {
		return false;
	}
	int line = fDocument.getLineOfOffset(offset - 1);
	return fDocument.getLineDelimiter(line) == null;
}
 
Example #19
Source File: TLAFastPartitioner.java    From tlaplus with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * May be replaced or extended by subclasses.
 * </p>
 */
public String getContentType(int offset) {
    checkInitialization();

    TypedPosition p= findClosestPosition(offset);
    if (p != null && p.includes(offset))
        return p.getType();

    return IDocument.DEFAULT_CONTENT_TYPE;
}
 
Example #20
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 #21
Source File: InlinedCssFormattingStrategy.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private String indentCssForXml(String formattedCssBlock, IDocument document,
    TypedPosition partition, String cssLineSeparator, String xmlLineSeparator)
    throws BadLocationException {

  String oneXmlIndent = computeOneXmlIndentString();

  int lineNumberInDocument = document.getLineOfOffset(partition.getOffset());
  int offsetOfLineInDocument = document.getLineOffset(lineNumberInDocument);
  String lineContents = document.get(offsetOfLineInDocument,
      document.getLineLength(lineNumberInDocument));
  int offsetOfNonwhitespaceInLine = StringUtilities.findNonwhitespaceCharacter(
      lineContents, 0);

  // The indent string that will be used for the closing tag </ui:style>
  String styleElementIndentString;
  // The indent string that will be used for to precede each line of the CSS
  // block
  String cssBlockIndentString;

  if (offsetOfLineInDocument + offsetOfNonwhitespaceInLine == partition.getOffset()) {
    // The CSS block is alone on this line, use whatever indentation it has
    cssBlockIndentString = lineContents.substring(0,
        offsetOfNonwhitespaceInLine);
    styleElementIndentString = cssBlockIndentString.replace(oneXmlIndent, "");

  } else {
    // Something else is before the CSS block on this line (likely the style
    // tag)
    styleElementIndentString = lineContents.substring(0,
        offsetOfNonwhitespaceInLine);
    cssBlockIndentString = styleElementIndentString + oneXmlIndent;
  }

  return processCssBlock(formattedCssBlock, cssLineSeparator,
      xmlLineSeparator, cssBlockIndentString, styleElementIndentString);
}
 
Example #22
Source File: TLAFastPartitioner.java    From tlaplus with MIT License 5 votes vote down vote up
/**
 * For printing out debugging information
 *   (TypedPosition)
 * @param msg
 */
public void debugPrint(String msg) {
    System.out.println("Debug print " + msg);
    System.out.println("Start comment offset: " + pcalStartCommentOffset
            + ";  Start: (" + pcalStartOffset + ", " + pcalStartLength + 
            ");  End comment: (" + pcalEndCommentOffset + ", "
            + pcalEndCommentLength + ")") ;
    Position[] positions = null;
    try {
        positions = fDocument.getPositions(fPositionCategory);
    } catch (BadPositionCategoryException e1) {
        System.out.println("Can't get positions") ;
        e1.printStackTrace();
        return ;
    }
    for (int i = 0; i < positions.length; i++) {
       try {
          TypedPosition position = (TypedPosition) positions[i] ;
          System.out.println("Position " + i + ": (" + position.getOffset()
                  + ", " + position.getLength() + ")  type: "
                  + position.getType() + (position.isDeleted?" DELETED":""));
          System.out.println("  `" + 
                  fDocument.get(position.getOffset(), position.getLength()) + "'") ;
    
       } catch (Exception e) {
            System.out.println("Item " + i + " Exception: " + e.getMessage()) ;
         }
    }
    IRegion result = createRegion();
    if (result == null) {
        System.out.println("Returned null");
    } else {
        System.out.println("Returned (" + result.getOffset() + ", " 
            + result.getLength() + ")") ;
    }
}
 
Example #23
Source File: AbstractFormattingStrategy.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void format() {
  super.format();

  IDocument document = documents.removeFirst();
  TypedPosition partition = partitions.removeFirst();

  if (document == null || partition == null) {
    return;
  }

  format(document, partition);
}
 
Example #24
Source File: AbstractFormattingStrategy.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void formatterStarts(IFormattingContext context) {
  super.formatterStarts(context);

  IDocument document = (IDocument) context.getProperty(FormattingContextProperties.CONTEXT_MEDIUM);
  TypedPosition position = (TypedPosition) context.getProperty(FormattingContextProperties.CONTEXT_PARTITION);

  partitions.addLast(position);
  documents.addLast(document);
}
 
Example #25
Source File: ExtractingGssFormattingStrategy.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected void format(IDocument document, TypedPosition partition) {

  GssExtractor extractor = GssExtractor.extract(document,
      partition.getOffset(), partition.getLength(),
      new GssResourceAwareModelLoader());
  if (extractor == null) {
    GWTPluginLog.logError("Could not format CSS block due to error in extracting the document.");
    return;
  }

  ICSSDocument cssDocument = extractor.getCssDocument();
  String formattedCssBlock = formatCss(cssDocument);

  formattedCssBlock = adjustFormattedCssWhitespace(formattedCssBlock,
      document, partition, extractor);
  if (formattedCssBlock == null) {
    return;
  }

  try {
    String currentText = document.get(partition.getOffset(),
        partition.getLength());

    if (formattedCssBlock.equals(currentText)) {
      // Do nothing
      return;
    }

    if (!StringUtilities.equalsIgnoreWhitespace(formattedCssBlock,
        currentText, true)) {
      // Do nothing, since the formatting cause non-whitespace/non-case
      // changes, which a formatter is not supposed to do
      // (Give it a dummy exception so it prints a stack trace)
      GWTPluginLog.logError(
          new Exception(),
          "Could not format text because the CSS formatter caused non-whitespace/non-case changes.  Please ensure your CSS is valid.");
      return;
    }

    document.replace(partition.getOffset(), partition.getLength(),
        formattedCssBlock.toString());
  } catch (BadLocationException e) {
    GWTPluginLog.logWarning(e, "Could not format CSS block.");
  }
}
 
Example #26
Source File: JavaFormatter.java    From goclipse with Eclipse Public License 1.0 4 votes vote down vote up
private List<TypedPosition> createRangeMarkers(TemplateVariable[] variables, IDocument document) throws MalformedTreeException, BadLocationException {
	Map<ReplaceEdit, String> markerToOriginal= new HashMap<ReplaceEdit, String>();

	MultiTextEdit root= new MultiTextEdit(0, document.getLength());
	List<TextEdit> edits= new ArrayList<TextEdit>();
	boolean hasModifications= false;
	for (int i= 0; i != variables.length; i++) {
		final TemplateVariable variable= variables[i];
		int[] offsets= variable.getOffsets();

		String value= variable.getDefaultValue();
		if (isWhitespaceVariable(value)) {
			// replace whitespace positions with unformattable comments
			String placeholder= COMMENT_START + value + COMMENT_END;
			for (int j= 0; j != offsets.length; j++) {
				ReplaceEdit replace= new ReplaceEdit(offsets[j], value.length(), placeholder);
				root.addChild(replace);
				hasModifications= true;
				markerToOriginal.put(replace, value);
				edits.add(replace);
			}
		} else {
			for (int j= 0; j != offsets.length; j++) {
				RangeMarker marker= new RangeMarker(offsets[j], value.length());
				root.addChild(marker);
				edits.add(marker);
			}
		}
	}

	if (hasModifications) {
		// update the document and convert the replaces to markers
		root.apply(document, TextEdit.UPDATE_REGIONS);
	}

	List<TypedPosition> positions= new ArrayList<TypedPosition>();
	for (Iterator<TextEdit> it= edits.iterator(); it.hasNext();) {
		TextEdit edit= it.next();
		try {
			// abuse TypedPosition to piggy back the original contents of the position
			final TypedPosition pos= new TypedPosition(edit.getOffset(), edit.getLength(), markerToOriginal.get(edit));
			document.addPosition(CATEGORY, pos);
			positions.add(pos);
		} catch (BadPositionCategoryException x) {
			Assert.isTrue(false);
		}
	}

	return positions;
}
 
Example #27
Source File: Bug369087Test.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
protected void assertSamePositionTypes(Position[] expected, Position[] actual) {
	assertEquals(expected.length, actual.length);
	for(int i=0; i<expected.length; ++i) 
		assertEquals(((TypedPosition)expected[i]).getType(), ((TypedPosition)actual[i]).getType());
}
 
Example #28
Source File: PartitionCodeReaderTest.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
public void testPartitionCodeReaderMarkBackwards() throws Exception {
    PartitionCodeReader reader = new PartitionCodeReader(IDocument.DEFAULT_CONTENT_TYPE);
    Document document = new Document("abcde");
    String category = setupDocument(document);

    document.addPosition(category, new TypedPosition(1, 1, "cat1")); //skip b
    document.addPosition(category, new TypedPosition(3, 1, "cat1")); //skip d

    reader.configureBackwardReader(document, document.getLength());
    int mark = reader.getMark();
    assertEquals(5, mark);
    assertEquals(reader.read(), 'e');

    int mark2 = reader.getMark();
    assertEquals(3, mark2);
    assertEquals(reader.read(), 'c');

    int mark3 = reader.getMark();
    assertEquals(1, mark3);
    assertEquals(reader.read(), 'a');

    int mark4 = reader.getMark();
    assertEquals(-1, mark4);
    assertEquals(reader.read(), -1);

    reader.setMark(mark);
    assertEquals(reader.read(), 'e');
    assertEquals(reader.read(), 'c');
    assertEquals(reader.read(), 'a');
    assertEquals(reader.read(), -1);

    reader.setMark(mark2);
    assertEquals(reader.read(), 'c');
    assertEquals(reader.read(), 'a');
    assertEquals(reader.read(), -1);

    reader.setMark(mark3);
    assertEquals(reader.read(), 'a');
    assertEquals(reader.read(), -1);

    reader.setMark(mark4);
    assertEquals(reader.read(), -1);
}
 
Example #29
Source File: PartitionCodeReaderTest.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
public void testPartitionCodeReaderMark() throws Exception {
    PartitionCodeReader reader = new PartitionCodeReader(IDocument.DEFAULT_CONTENT_TYPE);
    Document document = new Document("abcde");
    String category = setupDocument(document);

    document.addPosition(category, new TypedPosition(1, 1, "cat1")); //skip b
    document.addPosition(category, new TypedPosition(3, 1, "cat1")); //skip d

    reader.configureForwardReader(document, 0, document.getLength());
    int mark = reader.getMark();
    assertEquals(0, mark);
    assertEquals(reader.read(), 'a');

    int mark2 = reader.getMark();
    assertEquals(1, mark2);
    assertEquals(reader.read(), 'c');

    int mark3 = reader.getMark();
    assertEquals(3, mark3);
    assertEquals(reader.read(), 'e');

    int mark4 = reader.getMark();
    assertEquals(5, mark4);
    assertEquals(reader.read(), -1);

    reader.setMark(mark);
    assertEquals(reader.read(), 'a');
    assertEquals(reader.read(), 'c');
    assertEquals(reader.read(), 'e');
    assertEquals(reader.read(), -1);

    reader.setMark(mark2);
    assertEquals(reader.read(), 'c');
    assertEquals(reader.read(), 'e');
    assertEquals(reader.read(), -1);

    reader.setMark(mark3);
    assertEquals(reader.read(), 'e');
    assertEquals(reader.read(), -1);

    reader.setMark(mark4);
    assertEquals(reader.read(), -1);
}
 
Example #30
Source File: PartitionCodeReaderTest.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
public void testPartitionCodeReaderUnread() throws Exception {
    PartitionCodeReader reader = new PartitionCodeReader("cat1");
    Document document = new Document("abcde");
    String category = setupDocument(document);

    document.addPosition(category, new TypedPosition(1, 1, "cat1")); //skip b
    document.addPosition(category, new TypedPosition(3, 1, "cat1")); //skip d

    reader.configureForwardReader(document, 0, document.getLength(), true);

    assertEquals('b', reader.read());
    reader.unread();
    assertEquals('b', reader.read());
    reader.unread();

    assertEquals('b', reader.read());
    assertEquals('d', reader.read());
    assertEquals(-1, reader.read());
    reader.unread();
    assertEquals(-1, reader.read());
    reader.unread();
    assertEquals(-1, reader.read());
    reader.unread();
    reader.unread();
    assertEquals('d', reader.read());
    for (int i = 0; i < 5; i++) {
        reader.read(); //read past EOF (but should actually stay at EOF)
    }
    reader.unread();
    assertEquals(-1, reader.read());
    reader.unread();
    reader.unread();
    assertEquals('d', reader.read());
    for (int i = 0; i < 5; i++) {
        reader.unread(); //unread to the beggining
    }

    FastStringBuffer buf = new FastStringBuffer(document.getLength());
    readAll(reader, buf);
    reader.unread(); //EOF
    reader.unread(); //d
    reader.unread(); //b
    readAll(reader, buf);
    assertEquals("bdbd", buf.toString());

    reader.configureForwardReaderKeepingPositions(1, document.getLength());
    buf.clear();
    readAll(reader, buf);
    reader.unread(); //EOF
    reader.unread(); //d
    reader.unread(); //b
    readAll(reader, buf);
    assertEquals("bdbd", buf.toString());

    reader.configureForwardReaderKeepingPositions(2, document.getLength());
    buf.clear();
    readAll(reader, buf);
    reader.unread(); //EOF
    reader.unread(); //d
    reader.unread(); //b
    readAll(reader, buf);
    assertEquals("dd", buf.toString());
}