Entwickler-Ecke

Algorithmen, Optimierung und Assembler - Algorithmus zum Einrücken von PHP-Code


Jakob_Ullmann - Mi 10.10.07 12:41
Titel: Algorithmus zum Einrücken von PHP-Code
Hallo,

ich habe für mein laufendes Projekt einen Algorithmus zum Einrücken von PHP-Code erstellt. Den möchte ich eich nun mal vorstellen:

Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
procedure IndentCode(Edit: TSynEdit);
var i, j: Integer; deep: Integer; indent_spaces: string;
begin
  deep := 0;
  for i := 0 to Edit.Lines.Count - 1 do
  begin
    Edit.Lines[i] := Trim(Edit.Lines[i]);

    if Trim(Edit.Lines[i]) = '{' then
    begin
      Edit.Lines[i - 1] := Edit.Lines[i - 1] + ' {';
      deep := deep + 4;
      Edit.Lines.Delete(i);
    end;

    if (Copy(Edit.Lines[i],Length(Edit.Lines[i]),1) = '}'or (Copy(Edit.Lines[i],1,1) = '}')then
      deep := deep - 4;

    if (Copy(Edit.Lines[i],Length(Edit.Lines[i]),2) = '?>'or (Copy(Edit.Lines[i],1,2) = '?>')then
      deep := deep - 2;

    if Copy(trim(Edit.Lines[i]),1,4) = 'case' then
      deep := deep - 4;

    if Copy(trim(Edit.Lines[i]),1,7) = 'default' then
      deep := deep - 4;

    indent_spaces := '';

    for j := 1 to deep do
      indent_spaces := indent_spaces + ' ';

    Edit.Lines[i] := indent_spaces + Trim(Edit.Lines[i]);

    if Copy(Edit.Lines[i],Length(Edit.Lines[i]),1) = '{' then
      if Copy(Trim(Edit.Lines[i+1]),1,4) <> 'case' then
        deep := deep + 4;

    if Copy(trim(Edit.Lines[i]),1,4) = 'case' then
      deep := deep + 4;

    if Copy(trim(Edit.Lines[i]),1,7) = 'default' then
      deep := deep + 4;

    if Copy(Edit.Lines[i],Length(Edit.Lines[i])-4,4) = 'break;' then
      deep := deep - 4;

    if Copy(Edit.Lines[i],Length(Edit.Lines[i])-5,5) = '<?php' then
      deep := deep + 2;

  end;
end;


Das funktioniert sowohl bei uneingerücktem Code alsauch bei total wild eingerücktem Code:

Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
<?php
if ($a == $b)
{
echo "\$a \= \$b";
if ($b == $c) {
echo "\$a \= \$b \= \$c";
}
}

         switch ($a)
    {
                     case 2:
              echo "\$a \= 2";
                                  break;
        case 3:
                      echo "\$a \= 3";
             break;
    default:
                         echo "\$a ist weder 2, noch 3";
                    break;
}
?>


BenBE - Fr 12.10.07 14:30

Was ist dazu jetzt deine Frage?

Gut, und was machst Du bei Source, der nicht einmal Leerzeichen enthält (ich geb Dir gern ein Beispiel, falls nötig) ...