@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; }
@Override public void formatterStarts(final IFormattingContext context) { super.formatterStarts(context); final IDocument document = (IDocument) context.getProperty(FormattingContextProperties.CONTEXT_MEDIUM); final TypedPosition partition = (TypedPosition) context .getProperty(FormattingContextProperties.CONTEXT_PARTITION); final IProject project = (IProject) context.getProperty(ScriptFormattingContextProperties.CONTEXT_PROJECT); final String formatterId = (String) context.getProperty(ScriptFormattingContextProperties.CONTEXT_FORMATTER_ID); final Boolean isSlave = (Boolean) context .getProperty(ScriptFormattingContextProperties.CONTEXT_FORMATTER_IS_SLAVE); final Boolean canConsumeIndentation = isSlave != null && isSlave && (Boolean) context .getProperty(ScriptFormattingContextProperties.CONTEXT_FORMATTER_CAN_CONSUME_INDENTATION); final Boolean isSelection = !(Boolean) context.getProperty(FormattingContextProperties.CONTEXT_DOCUMENT); IRegion selectionRegion = null; if (isSelection != null && isSelection) { selectionRegion = (IRegion) context.getProperty(FormattingContextProperties.CONTEXT_REGION); } fJobs.addLast(new FormatJob(context, document, partition, project, formatterId, isSlave, canConsumeIndentation, isSelection, selectionRegion)); }
/** * @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()); } } }
/** * 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; }
private String getPartsWithPartition(IDocument document, String contentType) { Position[] positions = PartitionCodeReader.getDocumentTypedPositions(document, contentType); int total = 0; for (int i = 0; i < positions.length; i++) { Position position = positions[i]; total += position.length; } List<TypedPosition> sortAndMergePositions = PartitionMerger.sortAndMergePositions(positions, document.getLength()); FastStringBuffer buf = new FastStringBuffer(total + 5); for (TypedPosition typedPosition : sortAndMergePositions) { try { String string = document.get(typedPosition.getOffset(), typedPosition.getLength()); buf.append(string); } catch (BadLocationException e) { Log.log(e); } } return buf.toString(); }
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; }
/** * 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; }
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()); }
@Test public void testName() throws Exception { HashMap<String, String> javaFormattingPrefs = TestUtils.getJavaProperties(); int i = INPUT.indexOf("/*-"); int i2 = INPUT.indexOf("-*/"); TypedPosition partition = new TypedPosition(i, i2 - i + 3, ""); HashMap<String, String> jsMap = TestUtils.getJSProperties(); IDocument document = new Document(INPUT); JsniFormattingUtil jsniFormattingUtil = new JsniFormattingUtil(); TextEdit format1 = jsniFormattingUtil.format(document, partition, javaFormattingPrefs, jsMap, null); // TextEdit format1 = JsniFormattingUtil.format(document,javaFormattingPrefs, jsMap, null); format1.apply(document); Assert.assertEquals(FORMATTED, document.get()); System.err.println(FORMATTED); }
/** * {@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; }
/** * 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() + ")") ; } }
/** * {@inheritDoc} * <p> * May be replaced or extended by subclasses. * </p> * * @since 2.2 */ public String getContentType(int offset) { checkInitialization(); TypedPosition p = findClosestPosition(offset); if (p != null && p.includes(offset)) return p.getType(); return IDocument.DEFAULT_CONTENT_TYPE; }
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; }
/** * {@inheritDoc} * * <p>May be replaced or extended by subclasses. */ public String getContentType(int offset) { checkInitialization(); TypedPosition p = findClosestPosition(offset); if (p != null && p.includes(offset)) return p.getType(); return IDocument.DEFAULT_CONTENT_TYPE; }
@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); }
/** * 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; } }
/** * @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)); }
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; }
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()); }
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); }
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); }
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]); } }
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; }
@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."); } }
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."); } }
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; }
@Override public TypedPosition findClosestPosition(int offset) { return super.findClosestPosition(offset); }
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; }
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()); }
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); }
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); }