Difference between revisions of "Editor Macros PascalScript/ru"

From Lazarus wiki
Jump to navigationJump to search
Line 48: Line 48:
 
== Caller: TSynEdit ==
 
== Caller: TSynEdit ==
  
The following methods and properties are available:
+
Доступны следующие методы и свойства:
  
;Caret:  
+
;Caret (Каретка):  
 
     property CaretX: Integer;
 
     property CaretX: Integer;
 
     property CaretY: Integer;
 
     property CaretY: Integer;
Line 59: Line 59:
 
     procedure MoveLogicalCaretIgnoreEOL(const NewLogCaret: TPoint);
 
     procedure MoveLogicalCaretIgnoreEOL(const NewLogCaret: TPoint);
  
;Selection:
+
;Selection (Выделение):
 
     property BlockBegin: TPoint;
 
     property BlockBegin: TPoint;
 
     property BlockEnd: TPoint;
 
     property BlockEnd: TPoint;
     property SelAvail: Boolean; // read only
+
     property SelAvail: Boolean; // только для чтения
 
     property SelText: string;
 
     property SelText: string;
 
     property SelectionMode: TSynSelectionMode;
 
     property SelectionMode: TSynSelectionMode;
Line 73: Line 73:
  
  
;Search/Replace:
+
;Search/Replace (Поиск/Замена):
 
     function SearchReplace(const ASearch, AReplace: string; AOptions: TSynSearchOptions): integer;
 
     function SearchReplace(const ASearch, AReplace: string; AOptions: TSynSearchOptions): integer;
 
     function SearchReplaceEx(const ASearch, AReplace: string; AOptions: TSynSearchOptions; AStart: TPoint): integer;
 
     function SearchReplaceEx(const ASearch, AReplace: string; AOptions: TSynSearchOptions; AStart: TPoint): integer;
Line 80: Line 80:
 
     ( ssoMatchCase, ssoWholeWord,
 
     ( ssoMatchCase, ssoWholeWord,
 
       ssoBackwards,
 
       ssoBackwards,
       ssoEntireScope, ssoSelectedOnly,  // Default is From Caret to End-of-text (or begin-of-text if backward)  
+
       ssoEntireScope, ssoSelectedOnly,  // По умолчанию от [текущего положения] каретки до конца
       ssoReplace, ssoReplaceAll,        // Otherwise the function does a search only
+
                                        // текста (или к началу текста, если наоборот)
       ssoPrompt,                        // Show the prompt before replacing
+
       ssoReplace, ssoReplaceAll,        // В противном случае функция выполняет только поиск
       ssoSearchInReplacement,          // continue search-replace in replacement (with ssoReplaceAll) // replace recursive
+
       ssoPrompt,                        // Показывать приглашение перед заменой
 +
       ssoSearchInReplacement,          // продолжить поиск-замену в замещенном (с помощью ssoReplaceAll)/рекурсивная замена
 
       ssoRegExpr, ssoRegExprMultiLine,
 
       ssoRegExpr, ssoRegExprMultiLine,
       ssoFindContinue                  // Assume the current selection is the last match, and start search behind selection
+
       ssoFindContinue                  // Предположим, что текущее выделение является последним совпадением и
                                         // (before if ssoBackward) // Default is to start at caret (Only SearchReplace / SearchReplaceEx has start/end param)
+
                                         // начинается поиск позади выделения (впереди [выделения], если ssoBackward)
    );
+
                                        // По умолчанию [поиск] начинается с [текущего положения] каретки (только
 +
                                        // для SearchReplace/SearchReplaceEx, [который] имеет параметр start/end);
  
 
Returns the number of replacements done. When Searching, returns 1 if found, 0 if not found. If found the match will be selected (use BlockBegin/End).
 
Returns the number of replacements done. When Searching, returns 1 if found, 0 if not found. If found the match will be selected (use BlockBegin/End).
Line 95: Line 97:
 
   end;
 
   end;
  
;Text:
+
;Text (Текст):
 
     property Lines[Index: Integer]: string; // read only
 
     property Lines[Index: Integer]: string; // read only
 
     property LineAtCaret: string;  // read only
 
     property LineAtCaret: string;  // read only
Line 108: Line 110:
 
                                   );
 
                                   );
  
;Clipboard:
+
;Clipboard (Буфер обмена):
 
     procedure CopyToClipboard;
 
     procedure CopyToClipboard;
 
     procedure CutToClipboard;
 
     procedure CutToClipboard;
Line 114: Line 116:
 
     property CanPaste: Boolean    // read only
 
     property CanPaste: Boolean    // read only
  
;Logical / Physical:
+
;Logical / Physical (Логический / Физический):
 
     function LogicalToPhysicalPos(const p: TPoint): TPoint;
 
     function LogicalToPhysicalPos(const p: TPoint): TPoint;
 
     function LogicalToPhysicalCol(const Line: String; Index, LogicalPos
 
     function LogicalToPhysicalCol(const Line: String; Index, LogicalPos

Revision as of 08:23, 13 November 2018

English (en) русский (ru)


ENG: AT THE MOMENT THIS PAGE IS UNDER TRANSLATION.
RUS: В НАСТОЯЩИЙ МОМЕНТ СТРАНИЦА НАХОДИТСЯ В ПРОЦЕССЕ ПЕРЕВОДА.



Общее

Макросы PascalScript доступны в Lazarus 1.1 и более поздних версиях. Чтобы использовать эту функцию, вам необходимо установить пакет EditorMacroScript, который включает пакет Pascal Script. Pascal Script предоставляется объектами REM. Минимальный пакет предоставляется дистрибутивом Lazarus 1.1.

См. также IDE_Window:_Editor_Macros

Доступность

Эта функциональность доступна только на определенных платформах/архитектурах:

  • Windows
    • 32/64bit Intel/AMD
  • Linux
    • 32/64bit Intel/AMD
  • Mac
    • 32(/maybe 64)bit Intel/AMD
    • 32bit PPC

Простые действия

Все простые действия с клавиатурой представлены следующим образом:

ecLeft;
Перемещает каретку [на один символ] влево (в редакторе, который вызвал макрос)
ecChar('a');
Вставляет [символ] 'a'

См. модуль SynEditKeyCmds в пакете SynEdit и IDECommands в IDEIntf для [получения] полного списка. Или используйте Recorder для получения имен действий.

Функции

   Function MessageDlg( const Msg : string; DlgType : TMsgDlgType; Buttons : TMsgDlgButtons; HelpCtx : Longint) : Integer');
   Function MessageDlgPos( const Msg : string; DlgType : TMsgDlgType; Buttons : TMsgDlgButtons; HelpCtx : Longint; X, Y : Integer) : Integer');
   Function MessageDlgPosHelp( const Msg : string; DlgType : TMsgDlgType; Buttons : TMsgDlgButtons; HelpCtx : Longint; X, Y : Integer; const HelpFileName : string) : Integer');
   Procedure ShowMessage( const Msg : string);
   Procedure ShowMessagePos( const Msg : string; X, Y : Integer)');
   Function InputBox( const ACaption, APrompt, ADefault : string) : string');
   Function InputQuery( const ACaption, APrompt : string; var Value : string) : Boolean');

Представление объектов

Сценарии могут ссылаться на вызывающий SynEdit через идентификатор "Caller".

Caller: TSynEdit

Доступны следующие методы и свойства:

Caret (Каретка)
   property CaretX: Integer;
   property CaretY: Integer;
   property CaretXY: TPoint;
   property LogicalCaretXY: TPoint;
   property LogicalCaretX: Integer;
   procedure MoveCaretIgnoreEOL(const NewCaret: TPoint);
   procedure MoveLogicalCaretIgnoreEOL(const NewLogCaret: TPoint);
Selection (Выделение)
   property BlockBegin: TPoint;
   property BlockEnd: TPoint;
   property SelAvail: Boolean; // только для чтения
   property SelText: string;
   property SelectionMode: TSynSelectionMode;
   procedure ClearSelection;
   procedure SelectAll;
   procedure SelectToBrace;
   procedure SelectWord;
   procedure SelectLine(WithLeadSpaces: Boolean);
   procedure SelectParagraph;


Search/Replace (Поиск/Замена)
   function SearchReplace(const ASearch, AReplace: string; AOptions: TSynSearchOptions): integer;
   function SearchReplaceEx(const ASearch, AReplace: string; AOptions: TSynSearchOptions; AStart: TPoint): integer;
   TSynSearchOptions = set of
   ( ssoMatchCase, ssoWholeWord,
     ssoBackwards,
     ssoEntireScope, ssoSelectedOnly,  // По умолчанию от [текущего положения] каретки до конца 
                                       // текста (или к началу текста, если наоборот)
     ssoReplace, ssoReplaceAll,        // В противном случае функция выполняет только поиск
     ssoPrompt,                        // Показывать приглашение перед заменой
     ssoSearchInReplacement,           // продолжить поиск-замену в замещенном (с помощью ssoReplaceAll)/рекурсивная замена
     ssoRegExpr, ssoRegExprMultiLine,
     ssoFindContinue                   // Предположим, что текущее выделение является последним совпадением и 
                                       // начинается поиск позади выделения (впереди [выделения], если ssoBackward)
                                       // По умолчанию [поиск] начинается с [текущего положения] каретки (только 
                                       // для SearchReplace/SearchReplaceEx, [который] имеет параметр start/end);

Returns the number of replacements done. When Searching, returns 1 if found, 0 if not found. If found the match will be selected (use BlockBegin/End).

 if Caller.SearchReplace('FindMe', ' ', []) > 0 then begin
   // Selection is set to the first occurrence of FindMe (searched from position of caret)
 end;
Text (Текст)
   property Lines[Index: Integer]: string; // read only
   property LineAtCaret: string;  // read only
   procedure InsertTextAtCaret(aText: String; aCaretMode : TSynCaretAdjustMode);
   property TextBetweenPoints[aStartPoint, aEndPoint: TPoint]: String              // Logical Points
   procedure SetTextBetweenPoints(aStartPoint, aEndPoint: TPoint;
                                  const AValue: String;
                                  aFlags: TSynEditTextFlags = [];
                                  aCaretMode: TSynCaretAdjustMode;
                                  aMarksMode: TSynMarksAdjustMode;
                                  aSelectionMode: TSynSelectionMode
                                 );
Clipboard (Буфер обмена)
   procedure CopyToClipboard;
   procedure CutToClipboard;
   procedure PasteFromClipboard;
   property CanPaste: Boolean     // read only
Logical / Physical (Логический / Физический)
   function LogicalToPhysicalPos(const p: TPoint): TPoint;
   function LogicalToPhysicalCol(const Line: String; Index, LogicalPos
                             : integer): integer;
   function PhysicalToLogicalPos(const p: TPoint): TPoint;
   function PhysicalToLogicalCol(const Line: string;
                                 Index, PhysicalPos: integer): integer;
   function PhysicalLineLength(Line: String; Index: integer): integer;

ClipBoard: TClipBoard

   property AsText: String;

Example

The macro shown below aligns selected code to a specific token. It looks for a specific token in each selected line, and aligns each occurrence of it.

Select the 3 lines. If the selection starts right before the ":" then the ":" will be detected. A prompt will ask you to confirm the ":". Then all ":" will be aligned. (If you use a word for alignment, please note, that it will be matched regardless of word boundaries)

  text: string;
  a: Integer;
  foo: boolean

The macro:

function IsIdent(c: Char): Boolean;
begin
  Result := ((c >= 'a') and (c <= 'z')) or
            ((c >= 'A') and (c <= 'Z')) or
            ((c >= '0') and (c <= '9')) or
            (c = '_');
end;

var
  p1, p2: TPoint;
  s1, s2: string;
  i, j, k: Integer;
begin
  if not Caller.SelAvail then exit;
  p1 := Caller.BlockBegin;
  p2 := Caller.BlockEnd;
  if (p1.y > p2.y) or ((p1.y = p2.y) and (p1.x > p2.x)) then begin
    p1 := Caller.BlockEnd;
    p2 := Caller.BlockBegin;
  end;
  s1 := Caller.Lines[p1.y - 1];
  s2 := '';
  i := p1.x
  while (i <= length(s1)) and (s1[i] in [#9, ' ']) do inc(i);
  j := i;
  if i <= length(s1) then begin
    if IsIdent(s1[i]) then // pascal identifier
      while (i <= length(s1)) and IsIdent(s1[i]) do inc(i)
    else
      while (i <= length(s1)) and not(IsIdent(s1[i]) or (s1[i] in [#9, ' '])) do inc(i);
  end;
  if i > j then s2 := copy(s1, j, i-j);

  if not InputQuery( 'Align', 'Token', s2) then exit;

  j := 0;
  for i := p1.y to p2.y do begin
    s1 := Caller.Lines[i - 1];
    k := pos(s2, s1);
    if (k > j) then j := k;
  end;
  if j < 1 then exit;

  for i := p1.y to p2.y do begin
    s1 := Caller.Lines[i - 1];
    k := pos(s2, s1);
    if (k > 0) and (k < j) then begin
      Caller.LogicalCaretXY := Point(k, i);
      while k < j do begin
        ecChar(' ');
        inc(k);
      end;
    end;
  end;

end.


See http://forum.lazarus.freepascal.org/index.php/topic,27186.msg167883.html#msg167883 for counting array elements.