如何使用 OpenToolsAPI 在源代码编辑器中获取特定行字符串 (UTF8) 或特定行字符串长度



我想获取整个行字符串(UTF8)并想对行字符串进行操作。我已经尝试了以下代码。但是如果我们有多字节字符,则无法做到这一点。

J:=1;
  CurrentRowStr :='';
  while True do
  begin
    //detect end of line
    Buffer.EditPosition.Move(Changes[I].FLine,J);
    CurrentRowStr := CurrentRowStr + Buffer.EditPosition.Character ;
    J := J+1;
  end;
  CurrentRowStr := Buffer.EditPosition.Read(J-1);

如果有人可以帮助我使用 OpenToolsAPI 获取特定的行字符串,那将是非常有帮助的。

您可以使用IOTAEditReader来获取整行。以下代码来自我的转换帮助程序包。其中大部分都围绕着GetCurrentLineParams功能:

function GetEditor: IOTASourceEditor;
var
  ModuleServices: IOTAModuleServices;
  Module: IOTAModule;
  I: Integer;
begin
  ModuleServices := BorlandIDEServices as IOTAModuleServices;
  Module := ModuleServices.CurrentModule;
  for I := 0 to Module.GetModuleFileCount - 1 do
    if Supports(Module.GetModuleFileEditor(I), IOTASourceEditor, Result) then
      Break;
end;
function GetLineAtCharPos(const Editor: IOTASourceEditor;
  const EditView: IOTAEditView; CharPos: TOTACharPos): string;
var
  EditReader: IOTAEditReader;
  Start, Len: Integer;
  Res: AnsiString;
begin
  CharPos.CharIndex := 0;
  Start := EditView.CharPosToPos(CharPos);
  Inc(CharPos.Line);
  Len := EditView.CharPosToPos(CharPos) - Start;
  if Len > 0 then
  begin
    SetLength(Res, Len);
    EditReader := Editor.CreateReader;
    EditReader.GetText(Start, PAnsiChar(Res), Len);
    Result := string(PAnsiChar(Res));
  end;
end;
function GetCurrentLine(const Editor: IOTASourceEditor;
  var BufferStart, Index: LongInt): string;
var
  BufferLength: LongInt;
  EditReader: IOTAEditReader;
  Res: AnsiString;
begin
  GetCurrentLineParams(Editor, BufferStart, BufferLength, Index);
  SetLength(Res, BufferLength);
  EditReader := Editor.CreateReader;
  EditReader.GetText(BufferStart, PAnsiChar(Res), BufferLength);
  Result := string(PAnsiChar(Res)); // just to be sure.
end;
function GetCurrentCharPos(const Editor: IOTASourceEditor; out EditView:
  IOTAEditView): TOTACharPos;
var
  CursorPos: TOTAEditPos;
begin
  EditView := Editor.GetEditView(0);
  CursorPos := EditView.CursorPos;
  EditView.ConvertPos(True, CursorPos, Result);
end;
procedure GetCurrentLineParams(const Editor: IOTASourceEditor;
  var Start, Length, Index: Integer);
var
  EditView: IOTAEditView;
  CharPos: TOTACharPos;
begin
  CharPos := GetCurrentCharPos(Editor, EditView);
  Index := CharPos.CharIndex + 1;
  CharPos.CharIndex := 0;
  Start := EditView.CharPosToPos(CharPos);
  Inc(CharPos.Line);
  Length := EditView.CharPosToPos(CharPos) - Start;
end;
function GetCurrentLineStart(const Editor: IOTASourceEditor): Integer;
var
  L, I: Integer;
begin
  GetCurrentLineParams(Editor, Result, L, I);
end;
function GetCurrentLineLength(const Editor: IOTASourceEditor): Integer;
var
  S, I: Integer;
begin
  GetCurrentLineParams(Editor, S, Result, I);
end;

最新更新