unit StripComments;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Menus, IDECommands, SrcEditorIntf, IDEMsgIntf, RegExpr, IDEExternToolIntf, LazIDEIntf, MenuIntf;
procedure Register;
implementation
type
TStripComments = class
public
procedure AddPopupMenuItem(Sender: TObject);
end;
procedure TStripComments.AddPopupMenuItem(Sender: TObject);
var
SourceEditor: TSourceEditorInterface;
FileName, NewFileName: String;
FileContent: TStringList;
RegEx: TRegExpr;
i: Integer;
procedure RemoveExtraBlankLines(CodeLines: TStringList);
var
i: Integer;
BlankLineFound: Boolean;
begin
BlankLineFound := False;
i := 0;
while i < CodeLines.Count do
begin
if Trim(CodeLines[i]) = '' then
begin
if BlankLineFound then
CodeLines.Delete(i)
else
begin
BlankLineFound := True;
Inc(i);
end;
end
else
begin
BlankLineFound := False;
Inc(i);
end;
end;
end;
begin
SourceEditor := SourceEditorManagerIntf.ActiveEditor;
if Assigned(SourceEditor) then
begin
FileName := SourceEditor.FileName;
FileContent := TStringList.Create;
try
FileContent.Text := SourceEditor.SourceText;
RegEx := TRegExpr.Create;
RegEx.ModifierM := True;
try
// Strip single-line comments
RegEx.Expression := '\/\/.*';
RegEx.ModifierI := True; // case-insensitive
for i := 0 to FileContent.Count - 1 do
begin
if RegEx.Exec(FileContent[i]) then
FileContent[i] := StringReplace(FileContent[i], RegEx.Match[0], '', []);
end;
// Strip multi-line and Pascal-style block comments
RegEx.Expression := '[^'']\{\s*[^\s\$].*?\}|\(\*.*?\*\)';
RegEx.ModifierS := True;
FileContent.Text := RegEx.Replace(FileContent.Text, '', False);
finally
RegEx.Free;
end;
// Remove extra blank lines
RemoveExtraBlankLines(FileContent);
// Save the stripped content to a new file
NewFileName := ChangeFileExt(FileName, '_CmtFree.pas');
FileContent.SaveToFile(NewFileName);
// Provide some progress messages
IDEMessagesWindow.AddCustomMessage(mluNone, 'Comments stripped and saved to: ' + NewFileName);
IDEMessagesWindow.AddCustomMessage(mluNone, 'Opening the new file...');
// Open the new file in the IDE
LazarusIDE.DoOpenEditorFile(NewFileName, -1, -1, [ofAddToRecent]);
finally
FileContent.Free;
end;
end
else
begin
IDEMessagesWindow.AddCustomMessage(mluError, 'No active source editor found.');
end;
end;
procedure AddMenu;
var
ParentMenu: TIDEMenuSection;
StripComments: TStripComments;
begin
StripComments := TStripComments.Create;
// Find or create the parent menu section
ParentMenu := RegisterIDEMenuSection(mnuEdit, 'StripCommentsSection');
// Register the new menu item in the existing editor popup menu section
RegisterIDEMenuCommand(ParentMenu, 'StripOutComments', 'Remove Comments', @StripComments.AddPopupMenuItem);
end;
procedure Register;
begin
AddMenu;
end;
end.