Delphi-RAG-Lint
Open Tools API · Delphi 13.2

The IDE Formatter Hook in Delphi 13.2

Delphi 13.2 adds IOTACodeFormatter to the Open Tools API, a way to plug your own formatter into the IDE's Format Source command, and the only documentation is the comments in ToolsAPI.pas. This article shows how we used it to make YADF the IDE's own formatter, and how much buffer-handling code it lets a formatter drop.

Status

The integration described here is in YADF 1.0.21.0 (released 2026-11-03). It is opt-in and off by default. It compiles and its pure logic is unit-tested, but the live-IDE checklist has not been run yet. Section 07 lists what that checklist still has to confirm.

YADF is the Delphi source formatter we wrote because Micronite, the quality and production-control software we build for manufacturers, is a large Delphi code base, and we wanted one consistent layout across it. YADF runs as a command-line tool and inside the IDE as the YADFOT package. Until now the IDE side had to edit the editor buffer itself. Delphi 13.2 changes that.

01 — What is new

Two interfaces, documented only in the source

The ToolsAPI.pas that ships with 13.2 (source\ToolsAPI\ToolsAPI.pas, file date 2026-09-09) declares two new interfaces. We found no page for them in the product Help or on DocWiki. The XML doc-comments in the unit are the whole specification. Shortened:

TOTAMarkerOffsets = array of Cardinal;

IOTACodeFormatter = interface
  ['{F97625D3-1A5F-4FD9-9FA6-1BC8C8762CBB}']
  function HandleFile(const AFileName: string): Boolean;
  function FormatSelected(const AModule: IOTAModule; const AContent: UTF8String;
    ASelectedOffset, ASelectedLen: Integer; var ACursorOffset: Integer;
    var AFormattedText: UTF8String): Boolean;
  function FormatFile(const AModule: IOTAModule; const AContent: UTF8String;
    var ACursorOffset: Integer; var AFormattedText: UTF8String): Boolean;
  function FormatLine(const AModule: IOTAModule; const AEditorContent: IOTAEditorContent;
    const AContent: UTF8String; ASelectedOffset, ASelectedLen: Integer;
    var ACursorOffset: Integer; var AFormattedText: UTF8String): Boolean;
  function CanFormatLine(const AModule: IOTAModule; const AEdPos: TOTAEditPos;
    ANumLines: Integer): Boolean;
  function SupportsOffsetRemapping: Boolean;
  function CanFormatOnSave: Boolean;
  function GetConfirmDlg: Boolean;
  procedure SetConfirmDlg(AValue: Boolean);
  function GetConfirmDlgHintText: string;
  property ConfirmDlg: Boolean read GetConfirmDlg write SetConfirmDlg;
end;

IOTACodeFormatterServices370 = interface
  ['{68C04644-98D1-4C14-AB7C-2FA8834A670F}']
  procedure AddFormatter(const AFormatter: IOTACodeFormatter);
  procedure RemoveFormatter(const AFormatter: IOTACodeFormatter);
  function CanHandleFile(const AFileName: string): Boolean;
  function FormatActiveModule: Boolean;
  procedure AutoFormatLine(AView: IOTAEditView; const AEdPos: TOTAEditPos);
  function GetStoredOffsetsForFormatter(const AFormatter: IOTACodeFormatter): TOTAMarkerOffsets;
  procedure SetStoredOffsetsForFormatter(const AFormatter: IOTACodeFormatter;
    const AOffsets: TOTAMarkerOffsets);
end;

IOTACodeFormatterServices = interface(IOTACodeFormatterServices370)
  ['{F3474CD5-6EAB-472C-A6FE-635067C3E485}']
end;

The key point is in the signatures: the IDE gives the formatter the content as a UTF8String and takes back the result in var AFormattedText. The formatter never touches the editor buffer. The IDE applies the text itself.

The longest comments in the unit describe the offset-remapping contract. A formatter that returns True from SupportsOffsetRemapping reads the byte offsets of breakpoints, bookmarks and other gutter items with GetStoredOffsetsForFormatter, moves them to match the new text, and hands them back with SetStoredOffsetsForFormatter. If it does not, the comment says the IDE falls back to the original offsets.

02 — One package, every IDE

Gate on the declaration, not on the compiler version

YADFOT also builds for IDEs that do not have the new interfaces. VER370 is defined in 13.0, 13.1 and 13.2 alike, so it cannot tell them apart. The declaration can. The whole gate is one include file:

{ YADFOT.CodeFormatter.inc -- include AFTER `uses ToolsAPI` }
{$IF DECLARED(IOTACodeFormatter) and not DEFINED(YADF_NO_CODEFORMATTER)}
  {$DEFINE YADF_HAS_CODEFORMATTER}
{$IFEND}

DECLARED looks at what is in scope where the include sits, so the include must come after uses ToolsAPI. YADF_NO_CODEFORMATTER lets us force the old-IDE path in a 13.2 build to test it. The unit's public routines are declared unconditionally. On an older IDE they compile to no-ops, and the callers need no {$IF} of their own:

unit YADFOT.CodeFormatter;

interface

uses
  ToolsAPI;

{$I YADFOT.CodeFormatter.inc}

function CodeFormatterAvailable: Boolean;
procedure RegisterYadfCodeFormatter;
procedure UnregisterYadfCodeFormatter;

implementation

{$IFDEF YADF_HAS_CODEFORMATTER}
  // ... the real implementation (sections 03 and 04)
{$ELSE}
function CodeFormatterAvailable: Boolean;
begin
  Result:= False;
end;

procedure RegisterYadfCodeFormatter;
begin
  // Older IDE (no IOTACodeFormatter): nothing to register.
end;

procedure UnregisterYadfCodeFormatter;
begin
  // Older IDE: nothing was registered.
end;
{$ENDIF}

end.

The Options page shows its “Use YADF as the IDE code formatter (restart IDE)” check box only when CodeFormatterAvailable is True.

03 — Registration

AddFormatter on load, RemoveFormatter before the BPL goes

Registration is a Supports call on BorlandIDEServices and one AddFormatter. The formatter object is reference-counted. A unit-level variable holds our reference, and the IDE holds its own:

var
  GFormatter: IOTACodeFormatter = nil;

procedure RegisterYadfCodeFormatter;
var
  Svc: IOTACodeFormatterServices;
begin
  if GFormatter <> nil then Exit;
  if not LoadNativeFormatterFlag(ProfilesIniPath) then Exit;  // opt-in switch
  if not Supports(BorlandIDEServices, IOTACodeFormatterServices, Svc) then Exit;
  GFormatter:= TYadfCodeFormatter.Create;
  Svc.AddFormatter(GFormatter);
end;

procedure UnregisterYadfCodeFormatter;
var
  Svc: IOTACodeFormatterServices;
begin
  if GFormatter = nil then Exit;
  if Supports(BorlandIDEServices, IOTACodeFormatterServices, Svc) then
    try Svc.RemoveFormatter(GFormatter); except end;
  GFormatter:= nil;
end;

We call RegisterYadfCodeFormatter from the package's Register procedure. We call UnregisterYadfCodeFormatter from the wizard's Destroyed method, which runs before the package's code is unloaded, and again from finalization in case Destroyed never ran. Without it, the IDE would keep an interface whose methods live in a BPL that has been unloaded. Both calls are idempotent. The empty except covers a late IDE shutdown, when the service may already be gone.

04 — The formatter

Text in, text out

The whole adapter is a TInterfacedObject that implements IOTACodeFormatter. The method that does the work:

function TYadfCodeFormatter.FormatFile(const AModule: IOTAModule; const AContent: UTF8String;
  var ACursorOffset: Integer; var AFormattedText: UTF8String): Boolean;
var
  Declined: string;
  Text    : UTF8String;
begin
  Result:= False;
  try
    if not FormatUtf8Content(AContent, ResolveFProfileOptions, Text, Declined) then
    begin
      ReportProblem('buffer left unchanged -- the content guard declined the result.' +
        sLineBreak + Declined);
      Exit;
    end;
    ACursorOffset  := RemapCursorOffset(AContent, Text, ACursorOffset);
    AFormattedText := Text;
    Result:= True;
  except
    on E: Exception do
      ReportProblem('format failed.' + sLineBreak + E.ClassName + ': ' + E.Message);
  end;
end;

Returning False means “I did not format this”, so the IDE keeps the original text. YADF runs a content guard after every format. The guard checks the result against the original and declines when it finds a change that is not just layout. A decline or an exception therefore always ends in False. Partial or damaged text can never reach the editor.

HandleFile accepts .pas, .dpr, .dpk and .inc. The other members are deliberate refusals:

  • FormatSelected formats only when the selection covers the whole unit (Select All). Otherwise it shows a dialog and returns False. YADF needs the whole unit to work out indentation, and formatting a fragment out of context would shift its lines.
  • FormatLine and CanFormatLine return False, so the IDE never asks YADF to format line by line while you type.
  • SupportsOffsetRemapping returns False. A full remap of every gutter marker is future work. Until then the IDE falls back to the original offsets.
  • CanFormatOnSave returns False. YADF has no format-on-save option of its own.
05 — What it replaced

The code a formatter no longer needs

YADFOT's classic command (Tools menu and Ctrl+Shift+Alt+F) works on every IDE version, so it has to do everything itself. Below are the pieces of YADFOT.Wizard.pas that exist only to get text out of the editor and back in safely.

Reading the buffer in 4 KB chunks through IOTAEditReader, which returns UTF-8 bytes through an AnsiChar pointer:

Reader:= ASource.CreateReader;
repeat
  Got:= Reader.GetText(Pos, @Chunk[0], ChunkSize);
  if Got > 0 then
  begin
    SetLength(Utf8Bytes, CurLen + Got);
    Move(Chunk[0], Utf8Bytes[CurLen], Got);
    Inc(CurLen, Got);
    Inc(Pos   , Got);
  end;
until Got < ChunkSize;
Result:= TEncoding.UTF8.GetString(Utf8Bytes, 0, CurLen);

Writing it back through an undoable writer, so that Ctrl+Z restores the original:

Writer:= ASource.CreateUndoableWriter;
Writer.DeleteTo(MaxInt);
Utf8:= UTF8String(AText);
Writer.Insert(PAnsiChar(Utf8));

Saving and restoring the caret and scroll position, because replacing the whole buffer moves both to line 1. The saved line is clamped to the new line count.

Working around the Form Designer. This was the expensive one. In a unit with a .dfm, the designer keeps a map of source positions for the form class. Replacing the buffer leaves that map stale, and the next File > Save All raised an access violation inside TVCLRootDesigner.DoSave. So the classic command detects a form unit and takes a completely different route:

if ModuleHasFormDesigner(Editor) then
begin
  // 1. save the module, 2. format the FILE ON DISK,
  // 3. Module.Refresh(True) so editor and designer reload from clean source.
  FormatFormUnitViaReload(Editor, FileName, Opts);
  Exit;
end;

That route costs the user the undo step, which is why YADF writes a .BCK backup first.

Add the read-only buffer check, the active-editor lookup, a menu item and a key binding, and the classic command is a few hundred lines of IDE plumbing around one call to the formatting engine.

With IOTACodeFormatter none of this is ours to write. The IDE reads the buffer, applies the result, and owns the undo stack and the designer. It also owns the Format Source command and its shortcut. The adapter is one class whose working methods are about thirty lines in total. The rest is plain string code we can test outside the IDE (section 06). The classic command stays for older IDEs and for YADF's second profile, so on 13.2 both paths exist side by side.

06 — The testable half

Byte offsets, caret, selection: plain functions

The new interface passes content as UTF8String and positions as byte offsets into it, not as character indexes. So ACursorOffset has to stay a byte offset into the new text, and must never point into the middle of a multi-byte character. We put all of that in YADF.FormatBridge, a unit with no ToolsAPI and no VCL. It compiles in every IDE generation and is tested by a console program (Test\FormatBridgeTest.dpr):

function FormatUtf8Content(const AContent: UTF8String; const AOpts: TYadfOptions;
  out AFormatted: UTF8String; out ADeclined: string;
  AFormat: TYadfFormatFunc = nil): Boolean;   // never raises; False = original bytes back
function SelectionCoversWholeContent(const AContent: UTF8String;
  AOffset, ALen: Integer): Boolean;
function RemapCursorOffset(const AOriginal, AFormatted: UTF8String;
  AOffset: Integer): Integer;

RemapCursorOffset finds the caret's line index and byte column in the original, moves to the same line and column in the result (clamped to what exists), then steps back past UTF-8 continuation bytes:

Result:= S + Col;
while (Result > S) and (Result < LenB) and
      ((Byte(AFormatted[Result + 1]) and $C0) = $80) do
  Dec(Result);

Formatting can add or remove lines, so this only keeps the caret on the same line index. It does not track the exact token. That is enough to stop the editor jumping to line 1, and it is the reason we report SupportsOffsetRemapping = False rather than claim more.

The AFormat parameter is a test seam. The tests pass in a fake formatter that declines or raises, and check that the original bytes come back unchanged.

07 — Limits

What the source comments do not say

The comments in ToolsAPI.pas say what each method is for. They do not answer several questions a formatter author needs answered. These are our working assumptions, and each one is a step in the live-IDE checklist, which has not been run yet:

  • Offset base. We assume ASelectedOffset and ACursorOffset are 0-based, like IOTAEditReader.GetText. If they turn out to be 1-based, Select All will not be recognised as a whole-unit selection, and the “whole units only” dialog will appear instead.
  • Undo. We expect the IDE to record the whole format as one undo step.
  • Form units. We expect the IDE's own apply path to keep the Form Designer in sync, so the access violation from section 05 should not happen. This is the claim we most want to confirm.
  • Threading. We assume calls arrive on the main thread. The YADF engine is not thread-safe.
  • Several formatters. The services interface takes any number of formatters, but nothing says which one the IDE picks when two of them accept the same file.

To turn it on, check “Use YADF as the IDE code formatter (restart IDE)” on YADF's options page (it sets [IDE] NativeFormatter=1 in %APPDATA%\YADF\profiles.ini) and restart the IDE. Uncheck it and restart to get the IDE's own formatter back.

As of 2026-11-03: interface declarations are quoted from ToolsAPI.pas of RAD Studio 37.0 (Delphi 13.2), file date 2026-09-09, shortened to signatures. YADF code is quoted from release 1.0.21.0 (YADFOT.CodeFormatter.pas, YADFOT.CodeFormatter.inc, YADF.FormatBridge.pas, YADFOT.Wizard.pas), lightly trimmed. The integration shipped in YADF 1.0.21.0. Its live-IDE checklist had not been run when this was written.