I am working on a code-editor in java and i want to know how to auto-indent using brackets (open and close) like an actual code editor .
like this 1:
Array PrincipalVar = (Var => (OtherVar => (var3 => 3,
var4 => 8,
var6 => 1)
),
Var2 => (var => 1))
Editor is a JEditorPane. I tried some code, but nothing seem to work. I have already file contening code, and I want to Re-Indent this file. Code I already tried :
public String indentFileTry() throws FileNotFoundException{
LinkedList<Integer> inBracket = new LinkedList<Integer>();
String currentLine = "";
Scanner indent = new Scanner(new FileReader(f));
String ptu = "";
while(indent.hasNextLine()) {
currentLine = indent.nextLine();
currentLine = currentLine.trim();
char[] line = currentLine.toCharArray();
int i = 0;
while(i < line.length){ //Here I define the position of the Bracet for Indentation
if(line[i] == '('){
inBracket.addFirst(i);
}
i++;
}
if(!inBracket.isEmpty()){//here I indent with the position of the bracket and I remove the first(First In First Out)
if(!currentLine.contains(")")){
int spaceadded = 0;
String space ="";
while(spaceadded <= inBracket.getFirst()){
spaceadded++; space += " ";
}
currentLine = space + currentLine;
inBracket.removeFirst();
}else if(currentLine.contains(")")){
int spaceadded = 0;
String space ="";
while(spaceadded <= inBracket.getFirst()){
spaceadded++; space += " ";
}
currentLine = space + currentLine;
inBracket.removeFirst();
}
}
ptu += currentLine +"\n";
}
indent.close() ;
System.out.println(ptu);
return ptu;
}
For the response, What I do is easy. I made a LinkedList, and I use it like a FILO (First in Last out) like this :