Filtering results that will be displayed via Write / WriteLn lazarus / 62-General ---------------------------------------------------------------------- ASBzone · 2024-08-06 02:14 Hey, folks: I am trying to think of the best way to handle the following situation. The app will definitely be running in the Windows console, but I don't necessarily want to limit the answer to a Windows-only solution, but I'll take one that works. I have a series of WriteLn commands that are going to be used to display some output to the console.   I want to make it possible to allow someone to provide a search filter for a subset of this output and have it only display the lines that contain the search word/term. What would be the best approach to do this.   Would I be able to send the output to a buffer and the do the search from the buffer to the output? Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure ShowSyntax(const SearchFor: string); begin        WriteLn(SendTo, ' * Entering ', ThisApp.SName, ' with no parameters will display this help message.');        WriteLn(SendTo, ' * Parameters surrounded by <> are mandatory; Those surrounded by [] are optional.');        WriteLn(SendTo, ' * Parameters are case-insensitive, but may be shown in uppercase for clarity.');        WriteLn(SendTo, ' * Single- character parameters (e.g. -h) can be prefaced by "-" or "/".');      WriteLn(SendTo, ' * Multi-character parameters (e.g. --help) should be prefaced by "--".');        WriteLn(SendTo, ' * All parameters need to be separated from each other by at least one space.');        WriteLn(SendTo, ' * The -H, --?? --Version-Only and --Info parameters supersede all other options -- in that order.');        WriteLn(SendTo, ' * The -V parameter causes application build mode info to be shown whenever the banner is shown.');        WriteLn(SendTo, ' * Combining -H/-? and -V will display extended help info plus application exit/return codes.');        WriteLn(SendTo, ' * The --?? parameter behaves like the -H/-? and -V parameters combined.');        WriteLn(SendTo, ' * The --Info parameter will ONLY show the banner, with build info, and quit.  It will process no other data.');        WriteLn(SendTo, ' * The --Version-Only parameter behaves like the --Info parameter, but without showing the banner.');        WriteLn(SendTo, ' * The application banner is only displayed when Help Syntax is displayed, or when -B is used.', LINEENDING);end;  Example:  I want to make it possible that someone could filter this to show only the lines that contain the word "character" Thanks ---------------------------------------------------------------------- 440bx · 2024-08-06 03:49 I have example code that is 16 bit, it runs in Windows 3.1 (yes, 3.1... even before 9x) and Windows XP. It is tested and works but it must be compiled with a 16 bit compiler. I don't know if there is an FPC mode that emulates Turbo Pascal for Windows, Borland Pascal (which produced 16 bit Windows binaries) or Delphi 1.  If there is then it should be possible to compile and run that code.  Note: the "device" isn't Windows dependent, it is compiler-dependent.  The example program is definitely Windows only but doesn't matter. I believe, given the right information, FPC's structure of the File Interface Block, it is very easy to port it to 32 and 64 bit but, I don't have the necessary information about FPC to do it.  That part will have to be provided by someone else. The gist of the thing is to create an  output "device" that is custom managed.  This code shows how to do it in 16 bit:Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {$S-,R-,V- ,I-,B-,F-} {---------------------------------------------------------- -------------------}{  This unit implements functions to format strings using the Pascal procedure}{  Write.  It is *very* similar to the TurboPower Software TpStrDev unit.     }{                                                                           }{  It accomplishes this by sending the output of the Write procedure to a     }{  "device" that is actually a memory buffer.  The length of the string in the}{  buffer is retrieved using WWRetL (WinWrite Return Length).  The contents of}{  the buffer may be retrieved in three (3) different ways:                   }{                                                                           }{  1. As a PChar by calling WWRetZ (WinWrite Return asciiZ).                  }{  2. As a Pointer to a Pascal string by calling WWRetPSt (... Ret ^String)   }{  3. As a Pascal String by calling WWRetSt (... Return String)               }{                                                                         }{  The memory buffer is large enough to contain 257 characters, this size was }{  chosen to be: SizeOf(string) + 1.  + 1 so that even the largest string     }{  could be converted to an asciiz and thereby returned as either.  Note that }{  the length NEVER includes the trailing #0.                                 }{                                                                           }{  The routines in this unit have been tested under DOS and Windows.          }{  They have NOT been tested for protected mode operation under DOS.          }{                                                                           }{  LIMITATIONS:                                                             }{                                                                           }{  1. If the Write parameters sent to the buffer exceed the buffer size then  }{     the output is truncated. (Output buffer will have 257 bytes, 1 byte for }{     the length, 255 bytes of data and 1 trailing NULL byte).                }{                                                                           }{  2. Every execution of Pascal's Write resets the buffer therefore the     }{     formatted string must be created with a single call to Write.  In other }{     words, unlike TpStrDev, Write calls cannot be accumulated.              }{                                                                           }{  The above limitations were added to the original TpStrDev to avoid the     }{  possibility of infinite loops.                                             }{                                                                           }{  OTHER DIFFERENCES:                                                         }{                                                                           }{  1. The output buffer/string is NOT reset by the functions Return/Get.  This}{     allows the result to be used multiple times                           }{                                                                           }{  2. The resulting buffer/string may be interpreted as as Pascal string or as}{     a PChar.                                                              }{---------------- -------------------------------------------------------------} unit WinWrite;  { routines for reading and writing formatted strings                      } {--------------------------------------------------- --------------------------}INTERFACE{--------------------------------- --------------------------------------------} Type  PString = ^String; var  WW : text;              { the "Win-dows Write buffer" device                } function WWRetL : word;  { return the length of the string in the output buffer                      } function WWRetZ : PChar;  { return the address of the buffer as a pointer to char (PChar)             } function WWRetPSt : PString;  { return a pointer to a Pascal String                                       } function WWRetSt : string;  { return the contents of the buffer into a string                           } procedure WWGetSt (var s : string);  { copy the buffer contents into s                                         } { procedure WWGetZ (var p : pchar);                                         }{ not implemented.  use WWRetZ instead                                      } {----------------------------------- ------------------------------------------}IMPLEMENTATION{------------ -----------------------------------------------------------------} typ e  TextBuffer = array[0..65520] of Byte; { device buffer                     }   { structure of a Turbo File Interface Block --------------------------------}  FIB =   record            Handle    : Word;            Mode      : Word;            BufSize   : Word;          Private   : Word;            BufPos    : Word;            BufEnd    : Word;            BufPtr    : ^TextBuffer;            OpenProc  : Pointer;            InOutProc : Pointer;            FlushProc : Pointer;            CloseProc : Pointer;             { UserData  : array[1..16]  of Byte;   !! first byte used         }          Flushed   : boolean;            UserData  : array[1..15] of byte;             Name      : array[0..79]  of Char;            Buf     : array[0..127] of Char;          end; const  FMClosed  = $D7B0;  StrLenMax = sizeof(string) - 1;               { max string length         } var  WWBuffer: array [0..sizeof(string)] of char;  { 256 to allow for ending #0  }  StrBuf  : string absolute WWBuffer;  StrLen  : byte   absolute StrBuf;  {-------------------------------------------- ---------------------------------} function WWRetL : word;  { return the length of the string in the device buffer                      }begin  WWRetL := StrLen;                     { #0 is never included in the length  }end;  function WWRetZ : PChar;  { return the address of the buffer as a pointer to char (PChar)             }begin  WWRetZ := PChar(@StrBuf[1]);          { return a PChar                      }end;  function WWRetPSt : PString;  { return a pointer to a Pascal String                                       }begin  WWRetPSt := @StrBuf;                  { return a Pointer to a Pascal String }end;  function WWRetSt : string;  { return the contents of the buffer into a string                           }begin  WWRetSt := StrBuf;end;  procedure WWGetSt (var s : string);  { copy the buffer contents into s                                           }begin  s    := StrBuf;end; {---------------------------------------------------- -------------------------} function Out (var F : FIB) : Word; far;  { update the length byte of StrBuf                                        }var  Count : word;begin  Out := 0;   with F do begin     { if the Out function is being executed after a call to the Flush function}    { this indicates that we are processing a new write statement.  We need to}    { clear our buffer to make room for the new output of the write statement }     if Flushed then StrLen := 0;        { otherwise append to WWBuffer        }    Flushed                := FALSE;    { Flush function not executed yet     }     { move the bytes from Turbo's buffer F.buf to our buffer WWBuffer         }     if strlen + bufpos <= StrLenMax      then Count := bufpos      else Count := StrLenMax - StrLen;     if Count > 0 then      begin        move (buf[0], strbuf[strlen + 1], Count);        StrLen := StrLen + Count    end;     { let Turbo know that we are done with its buffer                       }     bufpos := 0;    bufend := 0;    WWBuffer[StrLen + 1] := #0;     { Turn our buffer into an asciiz string   }  end;end; function flush (var F : FIB) : Word; far;  { Just return Ok. Do nothing.                                               }begin  Flush := 0;   with F do    begin      Out(F);      Flushed := TRUE;    exit;    end;end;  function OpenClose (var F : FIB) : Word; far;  { Clear any text that may be laying around in the buffer                  }begin  with F do begin    BufPos  := 0;    BufEnd  := 0;  end;   OpenClose := 0;end; {------------------------------------------------- ----------------------------} procedure AssignBuf (var F : Text);  { initialize the File Interface Block                                     }begin  with FIB(F) do begin    Mode      := FMClosed;    OpenProc  := @OpenClose;    FlushProc := @Flush;    CloseProc := @OpenClose;  InOutProc := @Out;    BufEnd    := 0;    BufPos    := 0;    BufPtr    := @buf;    BufSize   := sizeof(buf);     Name[0]   := #0;     Flushed   := TRUE;                  { Flush function executed           }  end;end; {------------------------------------------------------ -----------------------} begin  AssignBuf (WW);  Rewrite   (WW);  StrLen := 0;end.The important part is the definition of the File Interface Block.  The code above uses the TP/BP definition that is valid in 16 bit.  I know there is an equivalent structure in FPC (I've seen it posted by PascalDragon but, I don't remember where and couldn't find it.) The first thing is to update that record definition. The "trick" is in the implementation of the "Out" function (which you might have to rename or prefix with an "&".)  That function can be customized to filter the output however you like. Example program in next post because with it the post was too long for the forum software. continued in next post... ---------------------------------------------------------------------- 440bx · 2024-08-06 03:51 continued from previous post... An example follows (which only compiles with a 16 bit compiler - TP/BP would work, Delphi 1 maybe, I'm not sure): Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program generic;  { generic template program used to incorporate examples of the "Windows API }  { bible                                                                   } {$R generic.res } uses WinTypes, WinProcs, Resources, WinWrite;  const  AppName = 'Generic'; {------------------- ----------------------------------------------------------} function ChildProc (Wnd    : hWnd;                  Msg    : word;                wParam : Word;                  lParam : LongInt) : LongInt; export;  { procedure for Child window.  Note that CHILD windows are never active!    }begin  { simply let the default window procedure take care of everything           }  case msg of    WM_MOUSEMOVE:     begin         SendMessage (GetParent (Wnd), msg, wparam, lParam);     end;  end;   ChildProc := DefWindowProc (Wnd, Msg, wParam, lParam);end; function InitChildClass (ChildClass : PChar) : Bool;  { registers the Child's window class                                      }var  cls : TWndClass; begin  if not GetClassInfo (hInstance, ChildClass, cls) then    begin      with cls do begin        style         := cs_VRedraw or cs_HRedraw;        lpfnWndProc     := @ChildProc;        cbClsExtra      := 0;        cbWndExtra      := 0;        hInstance       := system.hInstance;            { qualify instance!   }        hIcon           := LoadIcon (0, idi_Application);        hCursor         := LoadCursor (0, idc_Cross);        hbrBackground   := COLOR_WINDOW + 1;        lpszMenuName    := nil;                         { cannot have menu!   }        lpszClassName   := ChildClass;      end; { with }       InitChildClass := RegisterClass (cls);    end  else InitChildClass := True;end; {----------------------------------------------------------- ------------------} function WndProc (Wnd    : hWnd;                  Msg    : word;                  wParam : Word;                  lParam : LongInt) : LongInt; export;  { procedure for main window                                               }const  Text_1        : hWnd = 0;  Text_2        : hWnd = 0;  ChildWnd      : hWnd = 0; const  ChildClass    = 'ChildWindow'; var dc             : HDC; point          : TPOINT;  PointWnd       : hWnd;                 { window that contains the point      } WindowText     : array [0..255] of Char;  begin  WndProc := 0;                                 { default function result     }   case Msg of    WM_CREATE:       begin         Text_1 := CreateWindow ('STATIC',                                 'Static Text Window 1',                                 WS_CHILD or WS_VISIBLE or BS_PUSHBUTTON,                                  10,                                40,                                 140,                                20,                                 Wnd,                               100,           { Child ID ! not a menu       }                               hInstance,                                 nil);         if Text_1 = 0 then halt (255);          Text_2 := CreateWindow ('STATIC',                                 'Static Text Window 2',                                 WS_CHILD or WS_VISIBLE,                                10,                                  60,                                 140,                                  20,                                 Wnd,                               101,           { Child ID                    }                               hInstance,                                 nil);         if Text_2 = 0 then halt (255);          if not InitChildClass (ChildClass) then halt (255); { register it    }          ChildWnd := CreateWindow (ChildClass,                                   'ChildWindow',                                   WS_CHILD or WS_VISIBLE or                                   WS_BORDER or WS_CAPTION or WS_CLIPSIBLINGS,                                   70,                                 70,                                   240,                                   340,                                 Wnd,        { parent window                }                                 102,                                   hInstance,                                 nil);          exit;       end;     WM_MOUSEMOVE:       begin         point    := MAKEPOINT(lParam);       PointWnd := ChildWindowFromPoint (Wnd, point);         if PointWnd <> 0           then GetWindowText (PointWnd, WindowText, sizeof (WindowText))           else lstrcpy (WindowText,'<>'#0);        dc    := GetDC (Wnd);         Write (WW, 'Mouse Coordinates are: ', 'X: ', point.x:5,                                               'Y: ', point.y:5);         TextOut (dc, 400, 0, WWRetZ, WWRetL);         ReleaseDC (Wnd, dc);          dc    := GetDC (Wnd);         Write (WW, 'Child Window Text: ', WindowText);         TextOut (dc, 0, 0, WWRetZ, WWRetL);         ReleaseDC (Wnd, dc);          { do the same thing but using WindowFromPoint instead                }          PointWnd := WindowFromPoint (point);         if PointWnd <> 0         then GetWindowText (PointWnd, WindowText, sizeof (WindowText))         else lstrcpy (WindowText,'<>'#0);          dc    := GetDC (Wnd);         Write (WW, 'WindowFromPoint says: ', WindowText);       TextOut (dc, 0, 20, WWRetZ, WWRetL);         ReleaseDC (Wnd, dc);        exit;       end;      WM_COMMAND :       begin         case wParam of           IDM_QUIT :               begin                 DestroyWindow (Wnd);                 exit;               end;         end;       end;     WM_DESTROY :       begin         PostQuitMessage (0);                           { send WM_QUIT msg    }         exit;     end;  end; { case }   WndProc := DefWindowProc (Wnd, Msg, wParam, lParam);end;  function InitAppClass: Bool;  { registers the application's window classes                                }var  cls : TWndClass; begin  if not GetClassInfo (hInstance, AppName, cls) then    begin      with cls do begin        style           := cs_VRedraw or cs_HRedraw;        lpfnWndProc     := @WndProc;        cbClsExtra      := 0;        cbWndExtra      := 0;        hInstance     := system.hInstance;            { qualify instance!   }        hIcon           := LoadIcon (0, idi_Application);        hCursor       := LoadCursor (0, idc_Arrow);        hbrBackground   := COLOR_WINDOW + 1;        lpszMenuName    := AppName;        lpszClassName   := AppName;      end; { with }       InitAppClass := RegisterClass (cls);    end  else InitAppClass := True;end;  Function WinMain : integer;  { application entry point                                                 }var  Wnd : hWnd;  Msg : TMsg; begin  if not InitAppClass then Halt (255);  { register application's class        }   { Create the main application window                                      }   Wnd := CreateWindow (AppName,                 { class name                  }                       AppName,               { window caption text         }                       ws_OverlappedWindow or   { window style                }                     ws_clipchildren,                       cw_UseDefault,         { x pos on screen             }                       cw_UseDefault,           { y pos on screen             }                       cw_UseDefault,           { window width                }                     cw_UseDefault,           { window height               }                     0,                       { parent window handle      }                       0,                       { menu handle 0 = use class   }                       hInstance,               { instance handle             }                       Nil);                  { parameter sent to WM_CREATE }   if Wnd = 0 then halt;                       { could not create the window }   { the call to showwindow is not needed if ws_visible is specified in create }  { window call.  However, it should still be done so that the window is dis- }  { played according to the cmdShow parameter                               }   ShowWindow (Wnd, cmdShow);                    { make the window visible     }  UpdateWindow (Wnd);                         { send 1st WM_PAINT message   }    while GetMessage (Msg, 0, 0, 0) do            { wait for message            }    begin      TranslateMessage (Msg);                   { key conversions           }      DispatchMessage  (Msg);                   { send to window procedure    }    end;   WinMain := msg.wParam;                        { terminate with return code  }end; begin  WinMain;end.Notice the highlighted lines, those show how to use the custom output device. It would be quite easy to port the example program to FPC.  I believe that with the correct FPC equivalent of FIB, the unit would also be easy to port. HTH. NOTE: that code is a little older than 30 years old. ---------------------------------------------------------------------- dseligo · 2024-08-06 07:35 I would put those strings in some data structure and then search before outputting: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i const ThisAppSName = 'ThisAppSName'; var options: array of String =  (    ' * Entering ' + ThisAppSName + ' with no parameters will display this help message.',    ' * Parameters surrounded by <> are mandatory; Those surrounded by [] are optional.',    ' * Parameters are case- insensitive, but may be shown in uppercase for clarity.',    ' * Single-character parameters (e.g. -h) can be prefaced by "-" or "/".',    ' * Multi-character parameters (e.g. --help) should be prefaced by "--".',    ' * All parameters need to be separated from each other by at least one space.',    ' * The -H, --?? --Version-Only and --Info parameters supersede all other options -- in that order.',    ' * The -V parameter causes application build mode info to be shown whenever the banner is shown.',    ' * Combining -H/-? and -V will display extended help info plus application exit/return codes.',    ' * The --?? parameter behaves like the -H/-? and -V parameters combined.',    ' * The --Info parameter will ONLY show the banner, with build info, and quit.  It will process no other data.',    ' * The --Version-Only parameter behaves like the --Info parameter, but without showing the banner.',    ' * The application banner is only displayed when Help Syntax is displayed, or when -B is used.'  ); var i: Integer;    reg: TRegExpr; ...   For i := 0 to High(options) do    If Pos('character', LowerCase(Options[i])) > 0 then      WriteLn(Options[i]);   // or regex  reg := TRegExpr.Create;  reg.Expression := '.character.';  For i := 0 to High(options) do    If reg.Exec(Options[i]) then      WriteLn(Options[i]);  reg.Free; ---------------------------------------------------------------------- MarkMLl · 2024-08-06 07:54 Quote from: ASBzone on August 06, 2024, 04:14:17 amI am trying to think of the best way to handle the following situation. The app will definitely be running in the Windows console, but I don't necessarily want to limit the answer to a Windows-only solution, but I'll take one that works. I have a series of WriteLn commands that are going to be used to display some output to the console.   I want to make it possible to allow someone to provide a search filter for a subset of this output and have it only display the lines that contain the search word/term. What would be the best approach to do this.   Would I be able to send the output to a buffer and the do the search from the buffer to the output? You could do it by messing around at the TTextRec level, but this was intended to be opaque by the FPC developers and having been there (for a Telnet server and client) my experience is that there were reliability issues before FPC v3. I'd strongly recommend that you do not do that. Replace your WriteLn()s by something using either Str() or Format(), and (as suggested by 440bx) implement your own filtering. MarkMLl p.s. And don't try interleaving stuff going to OUTPUT and stdout, they're distinct. ---------------------------------------------------------------------- Thaddy · 2024-08-06 08:34 Quote from: MarkMLl on August 06, 2024, 09:54:39 amAnd don't try interleaving stuff going to OUTPUT and stdout, they're distinct. They are the same! It is an alias. That is clearly documented: https://www.freepascal.org/docs-html/rtl/system/stdout.html ---------------------------------------------------------------------- MarkMLl · 2024-08-06 08:36 Quote from: Thaddy on August 06, 2024, 10:34:08 amQuote from: MarkMLl on August 06, 2024, 09:54:39 amAnd don't try interleaving stuff going to OUTPUT and stdout, they're distinct. They are the same! It is an alias. That is clearly documented: https://www.freepascal.org/docs-html/rtl/system/stdout.html I didn't say StdOut, I said stdout. MarkMLl ---------------------------------------------------------------------- ASBzone · 2024-08-08 02:51 Quote from: 440bx on August 06, 2024, 05:51:04 amNOTE: that code is a little older than 30 years old. Can we consider this code millennial code? 😁😁 Thanks for this, 440bx.    I'll greatly appreciate this effort.  I will review and let you know if I have any questions. ---------------------------------------------------------------------- ASBzone · 2024-08-08 02:59 Quote from: MarkMLl on August 06, 2024, 09:54:39 amReplace your WriteLn()s by something using either Str() or Format(), and (as suggested by 440bx) implement your own filtering. MarkMLl p.s. And don't try interleaving stuff going to OUTPUT and stdout, they're distinct. Thanks, MarkMLl and Thaddy Also, thank you kindly, dseligo     I was originally going down this sort of path, but didn't think setup the array of strings that way. Lots to consider here.  I greatly appreciate it. ---------------------------------------------------------------------- 440bx · 2024-08-08 03:01 Quote from: ASBzone on August 08, 2024, 04:51:57 amThanks for this, 440bx.    I'll greatly appreciate this effort.  I will review and let you know if I have any questions. You're welcome.  The really important thing is to find the updated layout of the File Interface Block (the record that has the pointers that control the output device behavior.)  I vividly remember seeing it in a post by PascalDragon but, I can't find it nor where it is documented (I'm probably looking in all the wrong places.) Anyway, if you have any questions, I'll be glad to answer them. ---------------------------------------------------------------------- MarkMLl · 2024-08-08 08:02 Quote from: 440bx on August 08, 2024, 05:01:17 amYou're welcome.  The really important thing is to find the updated layout of the File Interface Block (the record that has the pointers that control the output device behavior.)  I vividly remember seeing it in a post by PascalDragon but, I can't find it nor where it is documented (I'm probably looking in all the wrong places.) That was probably related to a question I asked about 18 months ago relating to writing Telnet code. TextRec is documented as "not for application use" or similar, but his position was that it was a couple of steps removed from "if you're not part of the core team don't touch it". However it wasn't 100% straightforward, and I'd suggest not going down that path unless absolutely unavoidable. MarkMLl ---------------------------------------------------------------------- 440bx · 2024-08-08 09:04 Quote from: MarkMLl on August 08, 2024, 10:02:07 amTextRec is documented as "not for application use" or similar, but his position was that it was a couple of steps removed from "if you're not part of the core team don't touch it". Yes, that's it.  It's the layout of TextRec.  Now that you mentioned it, it was really easy to find Found the layout at https://www.freepascal.org/docs- html/rtl/system/textrec.html and as you stated it says "It should be treated as opaque and never manipulated directly." Now that I've read that, I am itching to port that old code to FPC.   x-rays are great to take care of opaque things ---------------------------------------------------------------------- Thaddy · 2024-08-08 09:36 Note that the TextRec layout is rather different from Delphi. When I did some tricks with it, I needed to write two separate versions to keep it working in Delphi too. ---------------------------------------------------------------------- MarkMLl · 2024-08-08 09:43 Quote from: Thaddy on August 08, 2024, 11:36:51 amNote that the TextRec layout is rather different from Delphi. When I did some tricks with it, I needed to write two separate versions to keep it working in Delphi too. Also I had problems with it using FPC < v3. (Context: a laptop I keep for debugging with relatively-old display hardware hence a relatively-old Debian version which encourages testing with GTK (as distinct from GTK2) hence an older Lazarus etc.). MarkMLl