Insert Blank Lines to Source Code By Using Eclipse JDT

This code example is for showing how to insert a blank line to Java source code by using eclipse JDT. The approach is similar with adding a statement or comment to source code, especially adding a comment.

It will insert a blank line before the first statement in the following code:

public class test {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("abc");
	}
}

After inserting a blank line, the code becomes like the following. Note there is a blank line before the first statement.

public class test {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
 
		System.out.println("abc");
	}
}

Steps for using the code example:
1. Create an eclipse Plug-in project. If you don’t know how to create a plug-in project, see “how to create a plug-in project tutorial“.
2. Copy the following method to your code.
3. Run your plug-in project, and create a java project named “testAddBlank” in the popup eclipse instance.
4. click the menu item that triggers the action.

//add a blank line before a statement
	private void AddBlankLine() throws MalformedTreeException, BadLocationException, CoreException {
 
		IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("testAddBlank");
		IJavaProject javaProject = JavaCore.create(project);
		IPackageFragment package1 = javaProject.getPackageFragments()[0];
 
		//get first compilation unit
		ICompilationUnit unit = package1.getCompilationUnits()[0];
 
		// parse compilation unit
		CompilationUnit astRoot = parse(unit);
 
		//create a ASTRewrite
		AST ast = astRoot.getAST();
		ASTRewrite rewriter = ASTRewrite.create(ast);
 
		//for getting insertion position
		TypeDeclaration typeDecl = (TypeDeclaration) astRoot.types().get(0);
		MethodDeclaration methodDecl = typeDecl.getMethods()[0];
		Block block = methodDecl.getBody();
 
		ListRewrite listRewrite = rewriter.getListRewrite(block, Block.STATEMENTS_PROPERTY);
		//notice here, we just create a string placeholder, and string is simply as empty
		Statement placeHolder = (Statement) rewriter.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT);
		listRewrite.insertFirst(placeHolder, null);
 
		TextEdit edits = rewriter.rewriteAST();
 
		// apply the text edits to the compilation unit
		Document document = new Document(unit.getSource());
 
		edits.apply(document);
 
		// this is the code for adding statements
		unit.getBuffer().setContents(document.get());
 
		System.out.println("done");
	}

parse method.

private static CompilationUnit parse(ICompilationUnit unit) {
		ASTParser parser = ASTParser.newParser(AST.JLS3);
		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		parser.setSource(unit);
		parser.setResolveBindings(true);
		return (CompilationUnit) parser.createAST(null); // parse
	}

Related Articles: