类org.eclipse.jface.text.TypedPosition源码实例Demo

下面列出了怎么用org.eclipse.jface.text.TypedPosition的API类实例代码及写法,或者点击链接到github查看源代码。

@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;
}
 
/**
 * @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));
}
 
/**
 * 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());
		}
	}
}
 
源代码4 项目: e4macs   文件: EmacsPlusUtils.java
/**
 * 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;
}
 
源代码5 项目: Pydev   文件: PartitionCodeReader.java
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;
}
 
源代码6 项目: Pydev   文件: PartitionCodeReader.java
/**
 * 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;
}
 
源代码7 项目: Pydev   文件: PartitionCodeReaderTest.java
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());
}
 
源代码8 项目: xtext-eclipse   文件: DocumentPartitioner.java
/**
 * {@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;
}
 
源代码9 项目: xtext-eclipse   文件: DocumentPartitioner.java
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;
}
 
源代码10 项目: tlaplus   文件: TLAFastPartitioner.java
/**
 * {@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;
}
 
源代码11 项目: tlaplus   文件: TLAFastPartitioner.java
/**
 * 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() + ")") ;
    }
}
 
@Override
public void format() {
  super.format();

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

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

  format(document, partition);
}
 
@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);
}
 
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);
}
 
源代码15 项目: gwt-eclipse-plugin   文件: JsniFormattingUtil.java
/**
 * 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;
  }
}
 
源代码16 项目: APICloud-Studio   文件: ScriptFormattingStrategy.java
/**
 * @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;
}
 
@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);
}
 
@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));
}
 
源代码19 项目: Pydev   文件: FastPartitioner.java
/**
 * {@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;
}
 
源代码20 项目: Pydev   文件: PartitionCodeReader.java
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;
}
 
源代码21 项目: Pydev   文件: PartitionCodeReaderTest.java
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());
}
 
源代码22 项目: Pydev   文件: PartitionCodeReaderTest.java
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);
}
 
源代码23 项目: Pydev   文件: PartitionCodeReaderTest.java
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);
}
 
源代码24 项目: goclipse   文件: LangPartitionScannerTest.java
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]);
	}
}
 
源代码25 项目: xtext-eclipse   文件: Bug369087Test.java
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());
}
 
@Override
protected void format(IDocument document, TypedPosition partition) {

  CssExtractor extractor = CssExtractor.extract(document,
      partition.getOffset(), partition.getLength(),
      new CssResourceAwareModelLoader());
  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.");
  }
}
 
源代码27 项目: gwt-eclipse-plugin   文件: JsniFormattingUtil.java
public static TextEdit format(IDocument document, TypedPosition partition,
    Map<String, String> javaFormattingPrefs,
    Map<String, String> javaScriptFormattingPrefs, String original) {
  try {
    // Extract the JSNI block out of the document
    int offset = partition.getOffset();
    int length = partition.getLength();

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

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

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

    String formattedJs;

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

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

    if (formatEdit != null) {

      body = restoreJsniJavaRefs(replacementResults);

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

      formattedJs = d.get();

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

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

      formattedJs = formattedJs + indentLine;

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

    } else {

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

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

    return new ReplaceEdit(offset, length, formattedJs);

  } catch (Exception e) {
    GWTPluginLog.logError(e);
    return null;
  }
}
 
@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.");
  }
}
 
源代码29 项目: APICloud-Studio   文件: DocumentScopeManager.java
private String getTokenScopeFragments(ITextViewer viewer, IDocument document, int offset)
{
	if (!(viewer instanceof ISourceViewer))
	{
		return null;
	}

	try
	{
		// Force adding the category in case it doesn't exist yet...
		document.addPositionCategory(ICommonConstants.SCOPE_CATEGORY);
		Position[] scopes = document.getPositions(ICommonConstants.SCOPE_CATEGORY);
		int index = document.computeIndexInCategory(ICommonConstants.SCOPE_CATEGORY, offset);

		if (scopes == null || scopes.length == 0)
		{
			return null;
		}
		if (index >= scopes.length)
		{
			index = scopes.length - 1;
		}
		Position scope = scopes[index];
		if (scope == null)
		{
			return null;
		}
		if (!scope.includes(offset))
		{
			if (index > 0)
			{
				scope = scopes[--index];
				if (scope == null || !scope.includes(offset))
				{
					return null;
				}
			}
			else
			{
				return null;
			}
		}
		if (scope instanceof TypedPosition)
		{
			TypedPosition pos = (TypedPosition) scope;
			return pos.getType();
		}
	}
	catch (Exception e)
	{
		IdeLog.logError(CommonEditorPlugin.getDefault(), e);
	}
	return null;
}
 
源代码30 项目: APICloud-Studio   文件: ExtendedFastPartitioner.java
@Override
public TypedPosition findClosestPosition(int offset) {
	return super.findClosestPosition(offset);
}
 
 类所在包
 同包方法