org.eclipse.jdt.core.formatter.IndentManipulation Java Examples

The following examples show how to use org.eclipse.jdt.core.formatter.IndentManipulation. 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: JavaDocCommentReader.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @see java.io.Reader#read()
 */
@Override
public int read() {
	if (fCurrPos < fEndPos) {
		char ch= getChar(fCurrPos++);
		if (fWasNewLine && !IndentManipulation.isLineDelimiterChar(ch)) {
			while (fCurrPos < fEndPos && Character.isWhitespace(ch)) {
				ch= getChar(fCurrPos++);
			}
			if (ch == '*') {
				if (fCurrPos < fEndPos) {
					do {
						ch= getChar(fCurrPos++);
					} while (ch == '*');
				} else {
					return -1;
				}
			}
		}
		fWasNewLine= IndentManipulation.isLineDelimiterChar(ch);

		return ch;
	}
	return -1;
}
 
Example #2
Source File: CreateTypeMemberOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private String removeIndentAndNewLines(String code, ICompilationUnit cu) throws JavaModelException {
	IJavaProject project = cu.getJavaProject();
	Map options = project.getOptions(true/*inherit JavaCore options*/);
	int tabWidth = IndentManipulation.getTabWidth(options);
	int indentWidth = IndentManipulation.getIndentWidth(options);
	int indent = IndentManipulation.measureIndentUnits(code, tabWidth, indentWidth);
	int firstNonWhiteSpace = -1;
	int length = code.length();
	while (firstNonWhiteSpace < length-1)
		if (!ScannerHelper.isWhitespace(code.charAt(++firstNonWhiteSpace)))
			break;
	int lastNonWhiteSpace = length;
	while (lastNonWhiteSpace > 0)
		if (!ScannerHelper.isWhitespace(code.charAt(--lastNonWhiteSpace)))
			break;
	String lineDelimiter = cu.findRecommendedLineSeparator();
	return IndentManipulation.changeIndent(code.substring(firstNonWhiteSpace, lastNonWhiteSpace+1), indent, tabWidth, indentWidth, "", lineDelimiter); //$NON-NLS-1$
}
 
Example #3
Source File: JavaDocCommentReader.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @see java.io.Reader#read()
 */
@Override
public int read() {
	if (fCurrPos < fEndPos) {
		char ch= fBuffer.getChar(fCurrPos++);
		if (fWasNewLine && !IndentManipulation.isLineDelimiterChar(ch)) {
			while (fCurrPos < fEndPos && Character.isWhitespace(ch)) {
				ch= fBuffer.getChar(fCurrPos++);
			}
			if (ch == '*') {
				if (fCurrPos < fEndPos) {
					do {
						ch= fBuffer.getChar(fCurrPos++);
					} while (ch == '*');
				} else {
					return -1;
				}
			}
		}
		fWasNewLine= IndentManipulation.isLineDelimiterChar(ch);

		return ch;
	}
	return -1;
}
 
Example #4
Source File: Strings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Removes leading tabs and spaces from the given string. If the string
 * doesn't contain any leading tabs or spaces then the string itself is
 * returned.
 * @param line the line
 * @return the trimmed line
 */
public static String trimLeadingTabsAndSpaces(String line) {
	int size= line.length();
	int start= size;
	for (int i= 0; i < size; i++) {
		char c= line.charAt(i);
		if (!IndentManipulation.isIndentChar(c)) {
			start= i;
			break;
		}
	}
	if (start == 0)
		return line;
	else if (start == size)
		return ""; //$NON-NLS-1$
	else
		return line.substring(start);
}
 
Example #5
Source File: Strings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static String trimTrailingTabsAndSpaces(String line) {
	int size= line.length();
	int end= size;
	for (int i= size - 1; i >= 0; i--) {
		char c= line.charAt(i);
		if (IndentManipulation.isIndentChar(c)) {
			end= i;
		} else {
			break;
		}
	}
	if (end == size)
		return line;
	else if (end == 0)
		return ""; //$NON-NLS-1$
	else
		return line.substring(0, end);
}
 
Example #6
Source File: OverrideCompletionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static String getIndentAt(IDocument document, int offset, CodeGenerationSettings settings) {
	try {
		IRegion region= document.getLineInformationOfOffset(offset);
		return IndentManipulation.extractIndentString(document.get(region.getOffset(), region.getLength()), settings.tabWidth, settings.indentWidth);
	} catch (BadLocationException e) {
		return ""; //$NON-NLS-1$
	}
}
 
Example #7
Source File: SourceModifier.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ReplaceEdit[] getModifications(String source) {
	List result= new ArrayList();
	int destIndentLevel= IndentManipulation.measureIndentUnits(this.destinationIndent, this.tabWidth, this.indentWidth);
	if (destIndentLevel == this.sourceIndentLevel) {
		return (ReplaceEdit[])result.toArray(new ReplaceEdit[result.size()]);
	}
	return IndentManipulation.getChangeIndentEdits(source, this.sourceIndentLevel, this.tabWidth, this.indentWidth, this.destinationIndent);
}
 
Example #8
Source File: ASTRewriteFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ASTRewriteFormatter(NodeInfoStore placeholders, RewriteEventStore eventStore, Map options, String lineDelimiter) {
	this.placeholders= placeholders;
	this.eventStore= eventStore;

	this.options= options == null ? JavaCore.getOptions() : (Map) new HashMap(options);
	this.options.put(
			DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_RESOURCES_IN_TRY,
			DefaultCodeFormatterConstants.createAlignmentValue(true, DefaultCodeFormatterConstants.WRAP_NEXT_PER_LINE, DefaultCodeFormatterConstants.INDENT_DEFAULT));

	this.lineDelimiter= lineDelimiter;

	this.tabWidth= IndentManipulation.getTabWidth(options);
	this.indentWidth= IndentManipulation.getIndentWidth(options);
}
 
Example #9
Source File: ASTRewriteAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private int findTagNameEnd(TagElement tagNode) {
	if (tagNode.getTagName() != null) {
		char[] cont= getContent();
	    int len= cont.length;
		int i= tagNode.getStartPosition();
		while (i < len && !IndentManipulation.isIndentChar(cont[i])) {
		    i++;
		}
		return i;
	}
    return tagNode.getStartPosition();
}
 
Example #10
Source File: ASTRewriteAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private int getCurrentLineStart(String str, int pos) {
	for (int i= pos - 1; i>= 0; i--) {
		char ch= str.charAt(i);
		if (IndentManipulation.isLineDelimiterChar(ch)) {
			return i+1;
		}
	}
	return 0;
}
 
Example #11
Source File: ASTRewriteAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean needsNewLineForLineComment(ASTNode node, String formatted, int offset) {
	if (!this.lineCommentEndOffsets.isEndOfLineComment(getExtendedEnd(node), this.content)) {
		return false;
	}
	// copied code ends with a line comment, but doesn't contain the new line
	return offset < formatted.length() && !IndentManipulation.isLineDelimiterChar(formatted.charAt(offset));
}
 
Example #12
Source File: ASTRewriteAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
final private String getIndentOfLine(int pos) {
	int line= getLineInformation().getLineOfOffset(pos);
	if (line >= 0) {
		char[] cont= getContent();
		int lineStart= getLineInformation().getLineOffset(line);
	    int i= lineStart;
		while (i < cont.length && IndentManipulation.isIndentChar(this.content[i])) {
		    i++;
		}
		return new String(cont, lineStart, i - lineStart);
	}
	return Util.EMPTY_STRING;
}
 
Example #13
Source File: OverrideCompletionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static String getIndentAt(IDocument document, int offset, CodeGenerationSettings settings) {
	try {
		IRegion region= document.getLineInformationOfOffset(offset);
		return IndentManipulation.extractIndentString(document.get(region.getOffset(), region.getLength()), settings.tabWidth, settings.indentWidth);
	} catch (BadLocationException e) {
		return ""; //$NON-NLS-1$
	}
}
 
Example #14
Source File: JavaElementLine.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @param element either an ICompilationUnit or an IClassFile
 * @param lineNumber the line number, starting at 0
 * @param lineStartOffset the start offset of the line
 * @throws CoreException thrown when accessing of the buffer failed
 */
public JavaElementLine(ITypeRoot element, int lineNumber, int lineStartOffset) throws CoreException {
	fElement= element;
	fFlags= 0;

	IBuffer buffer= element.getBuffer();
	if (buffer == null) {
		throw new CoreException(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, Messages.format( SearchMessages.JavaElementLine_error_nobuffer, BasicElementLabels.getFileName(element))));
	}

	int length= buffer.getLength();
	int i= lineStartOffset;

	char ch= buffer.getChar(i);
	while (lineStartOffset < length && IndentManipulation.isIndentChar(ch)) {
		ch= buffer.getChar(++i);
	}
	fLineStartOffset= i;

	StringBuffer buf= new StringBuffer();

	while (i < length && !IndentManipulation.isLineDelimiterChar(ch)) {
		if (Character.isISOControl(ch)) {
			buf.append(' ');
		} else {
			buf.append(ch);
		}
		i++;
		if (i < length)
			ch= buffer.getChar(i);
	}
	fLineContents= buf.toString();
	fLineNumber= lineNumber;
}
 
Example #15
Source File: JavaSearchPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private SearchPatternData trySimpleTextSelection(ITextSelection selection) {
	String selectedText= selection.getText();
	if (selectedText != null && selectedText.length() > 0) {
		int i= 0;
		while (i < selectedText.length() && !IndentManipulation.isLineDelimiterChar(selectedText.charAt(i))) {
			i++;
		}
		if (i > 0) {
			return new SearchPatternData(TYPE, REFERENCES, 0, fIsCaseSensitive, selectedText.substring(0, i), null, JavaSearchScopeFactory.ALL);
		}
	}
	return null;
}
 
Example #16
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static int getIndentUsed(IBuffer buffer, int offset, IJavaProject project) {
	int i= offset;
	// find beginning of line
	while (i > 0 && !IndentManipulation.isLineDelimiterChar(buffer.getChar(i - 1))) {
		i--;
	}
	return Strings.computeIndentUnits(buffer.getText(i, offset - i), project);
}
 
Example #17
Source File: NLSUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static int findLineEnd(ICompilationUnit cu, int position) throws JavaModelException {
	IBuffer buffer= cu.getBuffer();
	int length= buffer.getLength();
	for (int i= position; i < length; i++) {
		if (IndentManipulation.isLineDelimiterChar(buffer.getChar(i))) {
			return i;
		}
	}
	return length;
}
 
Example #18
Source File: JsniMethodBodyCompletionProposalComputer.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the indentation units for a given project, document, line and line
 * offset.
 */
static int measureIndentationUnits(IDocument document,
    int lineOfInvocationOffset, int lineOffset, IJavaProject project)
    throws BadLocationException {
  Map<?, ?> options = project.getOptions(true);
  String lineText = document.get(lineOffset,
      document.getLineLength(lineOfInvocationOffset));
  int indentationUnits = IndentManipulation.measureIndentUnits(lineText,
      IndentManipulation.getTabWidth(options),
      IndentManipulation.getIndentWidth(options));
  return indentationUnits;
}
 
Example #19
Source File: NLSUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static int findLineEnd(ICompilationUnit cu, int position) throws JavaModelException {
	IBuffer buffer= cu.getBuffer();
	int length= buffer.getLength();
	for (int i= position; i < length; i++) {
		if (IndentManipulation.isLineDelimiterChar(buffer.getChar(i))) {
			return i;
		}
	}
	return length;
}
 
Example #20
Source File: OverrideCompletionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public String updateReplacementString(IDocument document, int offset, ImportRewrite importRewrite,
		boolean snippetStringSupport)
				throws CoreException, BadLocationException {
	Document recoveredDocument= new Document();
	CompilationUnit unit= getRecoveredAST(document, offset, recoveredDocument);
	ImportRewriteContext context = new ContextSensitiveImportRewriteContext(unit, offset, importRewrite);

	ITypeBinding declaringType= null;
	ChildListPropertyDescriptor descriptor= null;
	ASTNode node= NodeFinder.perform(unit, offset, 1);
	node= ASTResolving.findParentType(node);
	String result = null;
	if (node instanceof AnonymousClassDeclaration) {
		declaringType= ((AnonymousClassDeclaration) node).resolveBinding();
		descriptor= AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY;
	} else if (node instanceof AbstractTypeDeclaration) {
		AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) node;
		descriptor= declaration.getBodyDeclarationsProperty();
		declaringType= declaration.resolveBinding();
	}
	if (declaringType != null) {
		ASTRewrite rewrite= ASTRewrite.create(unit.getAST());
		IMethodBinding methodToOverride= Bindings.findMethodInHierarchy(declaringType, fMethodName, fParamTypes);
		if (methodToOverride == null && declaringType.isInterface()) {
			methodToOverride= Bindings.findMethodInType(node.getAST().resolveWellKnownType("java.lang.Object"), fMethodName, fParamTypes); //$NON-NLS-1$
		}
		if (methodToOverride != null) {
			CodeGenerationSettings settings = PreferenceManager.getCodeGenerationSettings(fJavaProject.getProject());
			MethodDeclaration stub = StubUtility2Core.createImplementationStubCore(fCompilationUnit, rewrite, importRewrite,
					context, methodToOverride, declaringType, settings, declaringType.isInterface(), node,
					snippetStringSupport);
			ListRewrite rewriter= rewrite.getListRewrite(node, descriptor);
			rewriter.insertFirst(stub, null);

			ITrackedNodePosition position= rewrite.track(stub);
			try {
				Map<String, String> options = fJavaProject.getOptions(true);

				rewrite.rewriteAST(recoveredDocument, options).apply(recoveredDocument);

				String generatedCode = recoveredDocument.get(position.getStartPosition(), position.getLength());

				String indentAt = getIndentAt(recoveredDocument, position.getStartPosition(), settings);
				int generatedIndent = IndentManipulation.measureIndentUnits(indentAt, settings.tabWidth,
						settings.indentWidth);
				// Kinda fishy but empirical data shows Override needs to change indent by at
				// least 1
				generatedIndent = Math.max(1, generatedIndent);

				// Cancel generated code indent
				String delimiter = TextUtilities.getDefaultLineDelimiter(document);
				result = IndentManipulation.changeIndent(generatedCode, generatedIndent, settings.tabWidth,
						settings.indentWidth, "", delimiter);

			} catch (MalformedTreeException | BadLocationException exception) {
				JavaLanguageServerPlugin.logException("Unable to compute override proposal", exception);
			}
		}
	}
	return result;
}
 
Example #21
Source File: ASTRewriteFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public int computeIndentUnits(String line) {
	return IndentManipulation.measureIndentUnits(line, this.tabWidth, this.indentWidth);
}
 
Example #22
Source File: ASTRewriteFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public String changeIndent(String code, int codeIndentLevel, String newIndent) {
	return IndentManipulation.changeIndent(code, codeIndentLevel, this.tabWidth, this.indentWidth, newIndent, this.lineDelimiter);
}
 
Example #23
Source File: ASTRewriteFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public String getIndentString(String currentLine) {
	return IndentManipulation.extractIndentString(currentLine, this.tabWidth, this.indentWidth);
}
 
Example #24
Source File: LineCommentEndOffsets.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public boolean isEndOfLineComment(int offset, char[] content) {
	if (offset < 0 || (offset < content.length && !IndentManipulation.isLineDelimiterChar(content[offset]))) {
		return false;
	}
	return Arrays.binarySearch(getOffsets(), offset) >= 0;
}
 
Example #25
Source File: SelectionAwareSourceRangeComputer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private void initializeRanges() throws CoreException {
	fRanges = new HashMap<>();
	if (fSelectedNodes.length == 0) {
		return;
	}

	fRanges.put(fSelectedNodes[0], super.computeSourceRange(fSelectedNodes[0]));
	int last = fSelectedNodes.length - 1;
	fRanges.put(fSelectedNodes[last], super.computeSourceRange(fSelectedNodes[last]));

	IJavaProject javaProject = ((CompilationUnit) fSelectedNodes[0].getRoot()).getTypeRoot().getJavaProject();
	String sourceLevel = javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
	String complianceLevel = javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
	IScanner scanner = ToolFactory.createScanner(true, false, false, sourceLevel, complianceLevel);
	char[] source = fDocumentPortionToScan.toCharArray();
	scanner.setSource(source);
	fDocumentPortionToScan = null; // initializeRanges() is only called once

	TokenScanner tokenizer = new TokenScanner(scanner);
	int pos = tokenizer.getNextStartOffset(0, false);

	ASTNode currentNode = fSelectedNodes[0];
	int newStart = Math.min(fSelectionStart + pos, currentNode.getStartPosition());
	SourceRange range = fRanges.get(currentNode);
	fRanges.put(currentNode, new SourceRange(newStart, range.getLength() + range.getStartPosition() - newStart));

	currentNode = fSelectedNodes[last];
	int scannerStart = currentNode.getStartPosition() + currentNode.getLength() - fSelectionStart;
	tokenizer.setOffset(scannerStart);
	pos = scannerStart;
	int token = -1;
	try {
		while (true) {
			token = tokenizer.readNext(false);
			pos = tokenizer.getCurrentEndOffset();
		}
	} catch (CoreException e) {
	}
	if (token == ITerminalSymbols.TokenNameCOMMENT_LINE) {
		int index = pos - 1;
		while (index >= 0 && IndentManipulation.isLineDelimiterChar(source[index])) {
			pos--;
			index--;
		}
	}

	int newEnd = Math.max(fSelectionStart + pos, currentNode.getStartPosition() + currentNode.getLength());
	range = fRanges.get(currentNode);
	fRanges.put(currentNode, new SourceRange(range.getStartPosition(), newEnd - range.getStartPosition()));

	// The extended source range of the last child node can end after the selection.
	// We have to ensure that the source range of such child nodes is also capped by the selection range.
	// Example: (/*]*/TRANSFORMER::transform/*[*/)
	// Selection is between /*]*/ and /*[*/, but the extended range of the "transform" node actually includes /*[*/ as well.
	while (true) {
		List<ASTNode> children = ASTNodes.getChildren(currentNode);
		if (!children.isEmpty()) {
			ASTNode lastChild = children.get(children.size() - 1);
			SourceRange extRange = super.computeSourceRange(lastChild);
			if (extRange.getStartPosition() + extRange.getLength() > newEnd) {
				fRanges.put(lastChild, new SourceRange(extRange.getStartPosition(), newEnd - extRange.getStartPosition()));
				currentNode = lastChild;
				continue;
			}
		}
		break;
	}
}
 
Example #26
Source File: JsniFormattingUtil.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
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;
  }
}
 
Example #27
Source File: JsniFormattingUtil.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
private static int getLineIndentLevel(String line, int tabWidth,
    int indentWidth) {
  return IndentManipulation.measureIndentUnits(line, tabWidth, indentWidth);
}
 
Example #28
Source File: SelectionAwareSourceRangeComputer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void initializeRanges() throws CoreException {
	fRanges= new HashMap<ASTNode, SourceRange>();
	if (fSelectedNodes.length == 0)
		return;

	fRanges.put(fSelectedNodes[0], super.computeSourceRange(fSelectedNodes[0]));
	int last= fSelectedNodes.length - 1;
	fRanges.put(fSelectedNodes[last], super.computeSourceRange(fSelectedNodes[last]));

	IScanner scanner= ToolFactory.createScanner(true, false, false, false);
	char[] source= fDocumentPortionToScan.toCharArray();
	scanner.setSource(source);
	fDocumentPortionToScan= null; // initializeRanges() is only called once

	TokenScanner tokenizer= new TokenScanner(scanner);
	int pos= tokenizer.getNextStartOffset(0, false);

	ASTNode currentNode= fSelectedNodes[0];
	int newStart= Math.min(fSelectionStart + pos, currentNode.getStartPosition());
	SourceRange range= fRanges.get(currentNode);
	fRanges.put(currentNode, new SourceRange(newStart, range.getLength() + range.getStartPosition() - newStart));

	currentNode= fSelectedNodes[last];
	int scannerStart= currentNode.getStartPosition() + currentNode.getLength() - fSelectionStart;
	tokenizer.setOffset(scannerStart);
	pos= scannerStart;
	int token= -1;
	try {
		while (true) {
			token= tokenizer.readNext(false);
			pos= tokenizer.getCurrentEndOffset();
		}
	} catch (CoreException e) {
	}
	if (token == ITerminalSymbols.TokenNameCOMMENT_LINE) {
		int index= pos - 1;
		while (index >= 0 && IndentManipulation.isLineDelimiterChar(source[index])) {
			pos--;
			index--;
		}
	}

	int newEnd= Math.max(fSelectionStart + pos, currentNode.getStartPosition() + currentNode.getLength());
	range= fRanges.get(currentNode);
	fRanges.put(currentNode, new SourceRange(range.getStartPosition(), newEnd - range.getStartPosition()));
}
 
Example #29
Source File: StringFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static ReplaceEdit getReplace(int offset, int length, IBuffer buffer, boolean removeLeadingIndents) {

		String replaceString= new String();
		boolean hasMoreInComment= false;

		// look after the tag
		int next= offset + length;
		while (next < buffer.getLength()) {
			char ch= buffer.getChar(next);
			if (IndentManipulation.isIndentChar(ch)) {
				next++; // remove all whitespace
			} else if (IndentManipulation.isLineDelimiterChar(ch)) {
				length= next - offset;
				break;
			} else if (ch == '/') {
				next++;
				if (next == buffer.getLength() || buffer.getChar(next) != '/') {
					replaceString= "//"; //$NON-NLS-1$
				} else {
					length= next - offset - 1;
				}
				hasMoreInComment= true;
				break;
			} else {
				replaceString= "//"; //$NON-NLS-1$
				hasMoreInComment= true;
				break;
			}
		}
		if (!hasMoreInComment && removeLeadingIndents) {
			while (offset > 0 && IndentManipulation.isIndentChar(buffer.getChar(offset - 1))) {
				offset--;
				length++;
			}
		}
		if (length > 0) {
			ReplaceEdit replaceEdit= new ReplaceEdit(offset, length, replaceString);
			return replaceEdit;
		} else {
			return null;
		}
	}
 
Example #30
Source File: Strings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Returns the indent of the given string in indentation units. Odd spaces
 * are not counted.
 *
 * @param line the text line
 * @param project the java project from which to get the formatter
 *        preferences, or <code>null</code> for global preferences
 * @return the number of indent units
 * @since 3.1
 */
public static int computeIndentUnits(String line, IJavaProject project) {
	return IndentManipulation.measureIndentUnits(line, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project));
}