Главная страница
Top.Mail.Ru    Яндекс.Метрика
Текущий архив: 2007.07.22;
Скачать: CL | DM;

Вниз

Как сделать подсветку синтаксиса с помощью HIlightMemo?   Найти похожие ветки 

 
Greeg   (2006-12-11 11:45) [0]

Здравствуйте! Подскажите как правильно сделать подсветку синтаксиса в HIlightMemo! В OnScanToken как я не делал, всё не коректно получалось.


 
Vladimir Kladov   (2006-12-11 17:02) [1]

есть же пример вроде.


 
Greeg   (2006-12-11 21:53) [2]

Я не смог сделать, чтоб нормально подсвечивался синтаксис Паскаля! Была куча алгоритмов...Подсвечивается не всё! Мне нужен пример, чтоб хотябы begin подсвечивался нормально, иднентично Дельфийскому! Вот мой код...


function OnScanToken(Dumpy: Pointer; Sender: PControl; const FromPos: TPoint;
 var Attrs: TTokenAttrs): Integer;
var
 S, Word: String;
 Idx, Len, c: Integer;
 Ident: Boolean;
begin
 S := AnsiLowerCase(Editor.Edit.Lines[FromPos.Y]);
 Len := Length(S);
 Result := 0;
 Ident := FALSE;
 if S = "" then Exit;
 Idx := FromPos.X;
 for c := 0 to WordList.Count - 1 do begin //Список зарезе.слов
   Word := WordList.Items[c];
   if AnsiCompareStr(Copy(S, Idx + 1, Length(Word)), Word) = 0 then
     Ident := TRUE;

   while (Idx < Len) and not (S[Idx + 1] in TSynWordBreakChars) and (Length(Word) > Idx - FromPos.X) do
     Inc(Idx);
   if Ident then
     Break;
{    if Length(Word) < Idx - FromPos.X then
     Ident := FALSE;
}
 end;
//  Result := Idx - FromPos.X;
 Result := Length(Word);
 if Ident then begin
   Attrs.FontStyle := [fsBold];
   Attrs.FontColor := clNavy;
   Exit;
 end else begin
   Attrs.FontStyle := [];
   Attrs.FontColor := clWindowText;
 end;
 FormMain.StatusText[0] := PChar(Format("FromPos [%d, %d], Len %d", [FromPos.X, FromPos.Y, Len]));
end;


 
mdw ©   (2006-12-12 13:37) [3]

У меня примерно так реализовано. Не работают мнонгострочные коментарии, лениво делать:

type TTokens = (tNone, tReservedWord, tComment, tCharStr, tDigital);

const ReservedWordsCount = 72;
     ReservedWords: array [0..ReservedWordsCount-1]of string = (
                                              "and", "array", "as", "asm",
                                              "begin", "case", "class", "const",
                                              "constructor", "destructor", "dispinterface", "div",
                                              "do", "downto", "else", "end",
                                              "except", "exports", "file", "finalization",
                                              "finally", "for", "function", "goto",
                                              "if", "implementation", "in", "inherited",
                                              "initialization", "inline", "interface", "is",
                                              "label", "library", "mod", "nil",
                                              "not", "object", "of", "or",
                                              "out", "packed", "procedure", "program",
                                              "property", "raise", "record", "repeat",
                                              "resourcestring", "set", "shl", "shr",
                                              "string", "then", "threadvar", "to",
                                              "try", "type", "unit", "until",
                                              "uses", "var", "while", "with",
                                              "xor", "private", "protected", "public",
                                              "published", "automated", "at", "on"
                                              );

const Separators = " ;.,:=><()[]*+-/@^&#${}";

// {}  (* *)
function TCodesForm.ParseLine(ASource: String; APos: Integer; var ALength: Integer): TTokens;
var k: Integer;
   S: String;
begin
   Result:= tNone;
   ALength:= 1;
   ASource:= AnsiLowerCase(ASource);
   Delete(ASource, 1, APos-1);
   if ASource = "" then Exit;

   //Коментарии
   if Copy(ASource, 1, 2) = "//" then begin
     ALength:= Length(ASource);
     Result:= tComment;
     Exit;
   end;
   if (ASource[1] = "{") then begin
     ALength:= Pos("}", ASource);
     if ALength = 0 then ALength:= Length(ASource);
     Result:= tComment;
     Exit;
   end;

   //Строки
   if ASource[1] = """" then begin
     Delete(ASource, 1, 1);
     k:= Pos("""", ASource);
     if k = 0 then k:= Length(ASource);
     ALength:= k+1;
     Result:= tCharStr;
     Exit;
   end;
   if ASource[1] = "#" then begin
     ALength:= 1;
     while (Length(ASource)>ALength)and(ASource[ALength+1] in ["#", "0".."9"]) do inc(ALength);
     Result:= tCharStr;
     Exit;
   end;

   //Цифры
   if ASource[1] in ["$", "0".."9"] then begin
     ALength:= 1;
     while (Length(ASource)>ALength)and
           ((ASource[ALength+1] in [".", "0".."9"])or
            ((ASource[1]="$")and(ASource[ALength+1] in ["a".."f"]))) do inc(ALength);
     Result:= tDigital;
     Exit;
   end;

   S:= Parse(ASource, Separators);
   if FReservedWords.Find(S, k) then Result:= tReservedWord;
   ALength:= Max(1, Length(S));
end;

function TCodesForm.HEditScanToken(Sender: PControl; const FromPos: TPoint; var Attrs: TTokenAttrs): Integer;
begin
    Attrs.fontcolor := clWindowText;
    Attrs.fontstyle := [ ];
    case ParseLine(HEdit.Edit.Lines[FromPos.Y], FromPos.X+1, Result) of
      tReservedWord: Attrs.fontstyle:= [fsBold];
      tComment: begin
        Attrs.fontstyle:= [fsItalic];
        Attrs.fontcolor:= clGrayText;
      end;
      tCharStr: begin
        Attrs.fontstyle:= [];
        Attrs.fontcolor:= clFuchsia;
      end;
      tDigital: begin
        Attrs.fontstyle:= [];
        Attrs.fontcolor:= clBlue;
      end;
    end
end;


 
mdw ©   (2006-12-12 13:39) [4]

Де еще, где нибудь при создании:

   FReservedWords:= NewStrList;
   for i:= 0 to ReservedWordsCount-1 do ReservedWords.Add(ReservedWords[i]);
   FReservedWords.Sort(False);


 
Greeg   (2006-12-12 22:40) [5]

Большое спасибо, всё работает!!!



Страницы: 1 вся ветка

Текущий архив: 2007.07.22;
Скачать: CL | DM;

Наверх




Память: 0.49 MB
Время: 0.028 c
2-1182935082
Chaval'
2007-06-27 13:04
2007.07.22
OpenDialog


15-1182376985
IMHO
2007-06-21 02:03
2007.07.22
Слово о Вебмани (WebMoney)


3-1177134987
roman_ln
2007-04-21 09:56
2007.07.22
DBListBox1 список не активен


2-1182924390
_Asph
2007-06-27 10:06
2007.07.22
При перерисовке мелькает label


2-1183048916
Yurish
2007-06-28 20:41
2007.07.22
TClientSocket TServerSocket таковых в Делфи 7 нет?