Topic: memo or richEdit as code editor.

Hi.

I need your help.

I want to make a repo of short sql scripts and i wish to show the scripts formafted as a SQL Code  in a memo or richtext, like a Code Editor (with key words in color).

Is this posible?

Tanks in advance.

Re: memo or richEdit as code editor.

Yes it is possible. Use TdbRichEdit. I did the formatting and highlighting of the keywords that are recorded in the database with this script:

procedure frmImageEdit_TagTimer_OnTimer (Sender: TObject);
// обработка списка тегов в редакторе тегов
var
  i: integer;
  Tags: array of string;
  s: string;
  tmpTag: string;
  tmpETag: string;
begin
  TagTimer.Enabled := False; // оставновить таймер
  s := frmImageEdit.redTags.Text; // взять данные о тегах
  frmImageEdit.redTags.Clear; // очистить редактор
  // запятые заменить пробелами, убрать перевод строки и двойные пробелы
  s := ReplaceStr(s,',',' ');
  s := ReplaceStr(s,chr(13),' ');
  s := ReplaceStr(s,'  ',' ');
  Tags := SplitString( s,' '); // получить список тегов в виде строкового массива
  for i := 0 to length(Tags) - 1 do
  begin
    tmpTag := Trim(Tags[i]); // на всякий случай, чтобы остался только текст
    if (tmpTag <> '') then
    begin
      // ищем тег в базе
      tmpETag := VarToStr( SQLExecute('SELECT name FROM tag WHERE upper( name ) = upper("'+tmpTag+'")') );
      // если не найден, то
      if tmpETag = '' then
      begin // вставляем тег в написании пользователя, но с заглавной первой буквой, жёлтым цветом
        tmpTag := UpperCase(copy(tmpTag,1,1)) + copy(tmpTag,2,length(tmpTag)-1);
        frmImageEdit.redTags.InsertTextEx(tmpTag,$00FFFF,11,0,'Segoe UI')
      end // если найден, то вставляем в написании из базы, белым цветом
      else
        frmImageEdit.redTags.InsertTextEx(tmpETag,$FFFFFF,11,0,'Segoe UI');
     // добавляем пробел
     frmImageEdit.redTags.InsertTextEx(' ',$FFFFFF,11,0,'Segoe UI');
    end;
  end;
end;

The whole project is described here

Визуальное программирование: блог и телеграм-канал.

Re: memo or richEdit as code editor.

Hi,

Tanks a lot for your help.

I resolve with this code, but is very slow, some idea to perform this script?

 s := Form1.RichEdit1.Text;
  Form1.RichEdit1.Clear;

  s := ReplaceStr(s,'(',' (');
  s := ReplaceStr(s,chr(13),' ');
  s := ReplaceStr(s,'  ',' ');
  Tags := SplitString( s,' ');
  for i := 0 to length(Tags) - 1 do
  begin

     tmpTag := Trim(Tags[i]);
    if (tmpTag <> '') then
 begin
        if (UpperCase(tmpTag) = 'SELECT') or (UpperCase(tmpTag) = 'FROM')  or (UpperCase(tmpTag) = 'WHERE') or  (UpperCase(tmpTag) = 'LEFT') or (UpperCase(tmpTag) = 'RIGHT') or (UpperCase(tmpTag) = 'GROUP')  or (UpperCase(tmpTag) = 'ORDER') or (UpperCase(tmpTag) = 'HAVING') then
            begin
                ...
            end
        else if  (UpperCase(tmpTag) = 'JOIN') or (UpperCase(tmpTag) = 'BY') or (UpperCase(tmpTag) = 'OUTER') or (UpperCase(tmpTag) = 'INNER')  or (UpperCase(tmpTag) = 'AND') or (UpperCase(tmpTag) = 'OR') or (UpperCase(tmpTag) = 'AS') or (UpperCase(tmpTag) = 'ON') or (UpperCase(tmpTag) = 'NOT') or (UpperCase(tmpTag) = 'TOP') or (UpperCase(tmpTag) = 'DESC') or (UpperCase(tmpTag) = 'ASC') or (UpperCase(tmpTag) = 'BETWEEN') or (UpperCase(tmpTag) = 'LIKE') or (UpperCase(tmpTag) = 'EXTRACT')  or (UpperCase(tmpTag) = 'CASE') or (UpperCase(tmpTag) = 'WHEN')  or (UpperCase(tmpTag) = 'THEN')   or (UpperCase(tmpTag) = 'NULL') then
            begin
                ...
            end
        else if  (UpperCase(tmpTag) = 'SUM') or (UpperCase(tmpTag) = 'COUNT') or (UpperCase(tmpTag) = 'MIN') or (UpperCase(tmpTag) = 'MAX') or (UpperCase(tmpTag) = 'IN') or (UpperCase(tmpTag) = 'SUBSTR') or (UpperCase(tmpTag) = 'TO_DATE') then
            begin
                ...
            end
        else
            begin
               ...
            end

    end;
  end;

4 (edited by k245 2022-06-16 05:42:10)

Re: memo or richEdit as code editor.

rogrom wrote:

I resolve with this code, but is very slow, some idea to perform this script?

1) No need to call UpperCase() before each comparison, it's enough to do it when assigning a value to a variable.

tmpTag := UpperCase(Trim(Tags[i]));

2) Replace comparisons with lists.

var
  tmpList: TStringList;
...
  tmpList := TStringList.Create;
  tmpList.Add('SELECT');
  tmpList.Add('FROM');
  ...
  if tmpList.IndexOf( tmpTag ) >= 0 then
  begiin
  ...
  end;

This should not only improve performance, but also allow you to expand the dictionary without rewriting the code if you form a list from the base.


Try to avoid copy-paste when writing a program. Although this reduces the writing time, it leads to a decrease in the efficiency of the code and an increase in its volume.

Визуальное программирование: блог и телеграм-канал.

Re: memo or richEdit as code editor.

Tanks a lot for you help k245,

Your help was great, i optimize the code and use all your suggestions.