Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function PrettyFormat(const s: String; const AsHTML:Boolean): String;
- // Written by Lars Fosdal, September 2018
- var
- sEOL: string;
- sINDENT: string;
- LIndent: string;
- nIndent: Integer;
- procedure Dent;
- var ix: Integer;
- begin
- LIndent := '';
- for ix := 1 to nIndent
- do LIndent := LIndent + sINDENT;
- end;
- procedure Indent;
- begin
- Inc(nIndent);
- Dent;
- end;
- procedure Outdent;
- begin
- Dec(nIndent);
- Dent;
- end;
- var
- c: char;
- isInString: boolean;
- isEscape: boolean;
- isUnhandled: boolean;
- begin
- Result := '';
- nIndent := 0;
- if AsHTML
- then begin
- sEOL := '<br>';
- sINDENT := ' ';
- end
- else begin
- sEOL := #13#10;
- sINDENT := ' ';
- end;
- isInString := false;
- isEscape := false;
- LIndent := '';
- for c in s do
- begin
- if not isInString
- then begin
- isUnhandled := True;
- if ((c = '{') or (c = '['))
- then begin
- Indent;
- Result := Result + c + sEOL + LIndent;
- isUnhandled := False;
- end
- else if (c = ',')
- then begin
- Result := Result + c + sEOL + LIndent;
- isUnhandled := False;
- end
- else if ((c = '}') or (c = ']'))
- then begin
- Outdent;
- Result := Result + sEOL + LIndent + c;
- isUnhandled := False;
- end;
- if isUnhandled and not c.IsWhiteSpace
- then Result := Result + c;
- end
- else Result := Result + c;
- if not isEscape and (c = '"')
- then isInString := not isInString;
- isEscape := (c = '\') and not isEscape;
- end;
- end;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement