### TRouter Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/http-protocol-reference.md Demonstrates how to create a TRouter instance, add routes with handlers, and match URLs to retrieve parameters. ```pascal procedure HandleUserDetail(Match: TRouteMatch); var UserID: string; begin UserID := Match.Params.Values['id']; WriteLn('Getting user: ', UserID); end; var Router: TRouter; Match: TRouteMatch; begin Router := TRouter.Create; try Router.AddRoute('/users/:id', @HandleUserDetail); Router.AddRoute('/posts/:id/comments', nil); Match := Router.Match('/users/12345'); if Match <> nil then begin WriteLn('Matched route: ', Match.Pattern); WriteLn('User ID: ', Match.Params.Values['id']); end; finally Router.Free; end; end. ``` -------------------------------- ### FPC Documentation Directory Structure Example 1 Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/configuration-reference.md Illustrates a typical directory layout for FPC source and documentation. ```tree /FPC/ ├── fpcsrc/ │ ├── compiler/ │ ├── rtl/ │ ├── packages/ │ └── ... └── fpcdocs/ ├── xml/ # Documentation XML files ├── src/ # Documentation tools ├── examples/ # Example programs └── Makefile ``` -------------------------------- ### Current Date and Time Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/sysutils-api-reference.md Demonstrates calling Now, Date, Time, and GetTickCount64 to display current system information. ```pascal WriteLn('Current: ', Now); WriteLn('Today: ', Date); WriteLn('Time: ', Time); WriteLn('Startup: ', GetTickCount64, ' ms'); ``` -------------------------------- ### TQuery Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/database-api-reference.md Demonstrates how to create, configure, execute, and process results from a TQuery object. Use for parameterized SQL queries. ```pascal var Query: TQuery; begin Query := TQuery.Create(nil); try Query.DatabaseName := 'mydb'; Query.SQL.Text := 'SELECT * FROM users WHERE age > :MinAge ORDER BY name'; Query.Params.ParamByName('MinAge').AsInteger := 18; Query.Open; while not Query.Eof do begin WriteLn(Query.Fields['name'].AsString); Query.Next; end; finally Query.Close; Query.Free; end; end. ``` -------------------------------- ### TMemoryStream Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/classes-api-reference.md Demonstrates creating a TMemoryStream, writing data to it, saving it to a file, clearing it, and loading it back from a file. ```pascal var Mem: TMemoryStream; begin Mem := TMemoryStream.Create; try // Write data Mem.WriteBuffer(Data, SizeOf(Data)); // Save to file Mem.SaveToFile('output.dat'); // Clear and reload Mem.Clear; Mem.LoadFromFile('output.dat'); WriteLn('Size: ', Mem.Size); finally Mem.Free; end; end. ``` -------------------------------- ### FPC Documentation Directory Structure Example 2 Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/configuration-reference.md Shows an alternative directory layout where documentation is within a 'docs' folder. ```tree /FPC/ ├── compiler/ ├── rtl/ ├── packages/ ├── docs/ # This directory └── ... ``` -------------------------------- ### String Formatting Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/sysutils-api-reference.md Demonstrates how to use the Format function with various specifiers like %s, %d, %f, %x, and %b. ```pascal S := Format('Name: %s, Age: %d, Score: %.2f', ['Alice', 30, 95.5]); // Result: 'Name: Alice, Age: 30, Score: 95.50' S := Format('Hex: 0x%x, Binary: %b', [255, 15]); // Result: 'Hex: 0xff, Binary: 1111' ``` -------------------------------- ### TComponent Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/classes-api-reference.md Shows how to create components with an owner. When the owner component is freed, all its owned components are automatically freed as well. ```pascal var Owner: TComponent; Child1, Child2: TComponent; begin Owner := TComponent.Create(nil); try Child1 := TComponent.Create(Owner); Child2 := TComponent.Create(Owner); WriteLn('Children: ', Owner.ComponentCount); // 2 // No need to free Child1 or Child2 // Owner will free them finally Owner.Free; // Frees Owner and all children end; end. ``` -------------------------------- ### Date/Time Formatting Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/sysutils-api-reference.md Demonstrates using FormatDateTime with various format codes to customize date and time output. ```pascal DT := Now; WriteLn(FormatDateTime('yyyy-mm-dd', DT)); // 2024-12-31 WriteLn(FormatDateTime('dd/mm/yyyy hh:nn:ss', DT)); // 31/12/2024 14:30:45 WriteLn(FormatDateTime('dddd, mmmm d, yyyy', DT)); // Monday, December 31, 2024 WriteLn(FormatDateTime('h:n AM/PM', DT)); // 2:30 PM ``` -------------------------------- ### FPC Documentation XML Schema Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/configuration-reference.md Example of the fpdoc XML schema structure for documenting packages, modules, and elements. ```xml One-line description

Extended description with HTML-like tags.

  • List item
Topic title Topic description Short description Detailed description
``` -------------------------------- ### TResponse Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/http-protocol-reference.md Demonstrates how to create a TResponse object, set its properties, add headers and cookies, and prepare a response. Remember to free the Response object when done. ```pascal var Response: TResponse; Cookie: TCookie; begin Response := TResponse.Create(Request); try // Set response code and content Response.Code := 200; Response.ContentType := 'application/json'; Response.Content := '{"status": "ok"}'; // Add header Response.SetHeader('X-Custom-Header', 'custom-value'); // Set cookie Cookie := TCookie.Create; Cookie.Name := 'session_id'; Cookie.Value := 'abc123xyz'; Cookie.Expires := IncDay(Now); Response.SetCookie(Cookie); // Redirect // Response.Redirect('https://example.com/success', 301); finally Response.Free; end; end. ``` -------------------------------- ### Date/Time Conversion Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/sysutils-api-reference.md Illustrates parsing strings into TDateTime objects and formatting TDateTime objects back into strings. ```pascal D := StrToDate('2024-12-31'); T := StrToTime('14:30:45'); DT := StrToDateTime('2024-12-31 14:30:45'); WriteLn(DateToStr(Now)); // 31/12/2024 WriteLn(TimeToStr(Time)); // 14:30:45 WriteLn(DateTimeToStr(Now)); // 31/12/2024 14:30:45 ``` -------------------------------- ### TDatabase Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/database-api-reference.md Illustrates creating, connecting, and disconnecting a TDatabase instance. Use for general database connection management. ```pascal var Database: TDatabase; begin Database := TDatabase.Create(nil); try Database.DatabaseName := 'defaultdb'; Database.Params.Text := 'Server=localhost;User=admin;Password=secret'; Database.Open; WriteLn('Connected: ', Database.Connected); WriteLn('Version: ', Database.Version); // Use database... finally Database.Close; Database.Free; end; end. ``` -------------------------------- ### TCustomSession Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/http-protocol-reference.md Demonstrates how to create a TCustomSession instance, set session variables, retrieve them, and check if the session has expired. ```pascal var Session: TCustomSession; begin Session := TCustomSession.Create(nil); try Session.SessionID := GenerateUniqueID(); Session.TimeOutMinutes := 30; // Store session data Session.Variables['user_id'] := '12345'; Session.Variables['username'] := 'john_doe'; // Retrieve WriteLn('User: ', Session.Variables['username']); // Check expiration if Session.IsExpired then WriteLn('Session expired'); finally Session.Free; end; end. ``` -------------------------------- ### Execute Process Asynchronously Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/process-api-reference.md Starts a process and returns immediately, allowing the application to continue. Use a loop with `Running` property or `WaitOnExit` to determine completion. ```pascal var Process: TProcess; begin Process := TProcess.Create(nil); try Process.Executable := '/usr/bin/ls'; Process.Parameters.Add('-la'); Process.Execute; while Process.Running do Sleep(100); WriteLn('Exit code: ', Process.ExitCode); finally Process.Free; end; end. ``` -------------------------------- ### TProcess.Execute Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/process-api-reference.md Starts the process and returns immediately. The caller should monitor the `Running` property or call `WaitOnExit()` to determine completion. ```APIDOC ## TProcess.Execute ### Description Starts the process and returns immediately. Check `Running` property or call `WaitOnExit()`. ### Method `procedure Execute; ` ### Parameters None ### Returns None ### Usage ```pascal var Process: TProcess; begin Process := TProcess.Create(nil); try Process.Executable := '/usr/bin/ls'; Process.Parameters.Add('-la'); Process.Execute; while Process.Running do Sleep(100); WriteLn('Exit code: ', Process.ExitCode); finally Process.Free; end; end. ``` ``` -------------------------------- ### Line Break Handling Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/sysutils-api-reference.md Shows how to convert line breaks to the platform standard or a specific style like Unix (LF). ```pascal // Convert all line breaks to platform standard Normalized := AdjustLineBreaks(S); // Convert to Unix line breaks UnixStyle := AdjustLineBreaks(S, tlbsLF); ``` -------------------------------- ### MySQL/MariaDB Connection Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/database-api-reference.md Demonstrates establishing a connection to a MySQL or MariaDB database using TSQLConnection. Requires ConnectorType set to 'mysql'. ```pascal var Conn: TSQLConnection; begin Conn := TSQLConnection.Create(nil); try Conn.ConnectorType := 'mysql'; Conn.HostName := 'localhost'; Conn.DatabaseName := 'mydatabase'; Conn.UserName := 'root'; Conn.Password := 'password'; Conn.Port := 3306; Conn.Open; finally Conn.Close; Conn.Free; end; end. ``` -------------------------------- ### FPJSON Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/fpjson-api-reference.md Demonstrates creating a JSON object, adding string and integer values, checking its type, formatting it to a JSON string, and finding a nested value by path. ```pascal uses fpjson; var Obj: TJSONObject; Val: TJSONData; begin // Create an object Obj := TJSONObject.Create; Obj.Add('Name', TJSONString.Create('Alice')); Obj.Add('Age', TJSONIntegerNumber.Create(30)); // Get type information WriteLn(Obj.JSONType = jtObject); // True // Format as JSON WriteLn(Obj.FormatJSON()); // Find nested data Val := Obj.FindPath('Name'); if Val <> nil then WriteLn('Found: ', Val.AsString); Obj.Free; end. ``` -------------------------------- ### TFileStream Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/classes-api-reference.md Demonstrates how to create, write to, and read from a file using TFileStream. Ensure to free the stream instance after use. ```pascal var File: TFileStream; begin // Create/overwrite file File := TFileStream.Create('data.bin', fmCreate); try File.Write(Data, SizeOf(Data)); finally File.Free; end; // Read from file File := TFileStream.Create('data.bin', fmOpenRead); try File.ReadBuffer(Data, SizeOf(Data)); finally File.Free; end; end. ``` -------------------------------- ### TList Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/classes-api-reference.md Demonstrates basic usage of the TList class, including creation, adding items, checking count, finding an index, and clearing the list. Remember to free the list when done. ```pascal var L: TList; P: Pointer; begin L := TList.Create; try L.Add(Pointer(100)); L.Add(Pointer(200)); WriteLn('Count: ', L.Count); WriteLn('Index of 200: ', L.IndexOf(Pointer(200))); L.Clear; finally L.Free; end; end. ``` -------------------------------- ### Move to First Record Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/database-api-reference.md Navigates the dataset cursor to the first record. Use this to start iteration from the beginning. ```pascal procedure First; ``` -------------------------------- ### TProcess.Run Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/process-api-reference.md Starts the process and waits for its completion, returning the process's exit code. ```APIDOC ## TProcess.Run ### Description Starts process and waits for completion. Returns exit code. ### Method `function Run: Integer; ` ### Parameters None ### Returns `Integer` - process exit code ### Usage ```pascal var Process: TProcess; ExitCode: Integer; begin Process := TProcess.Create(nil); try Process.Executable := 'gcc'; Process.Parameters.Add('-o'); Process.Parameters.Add('program'); Process.Parameters.Add('main.c'); ExitCode := Process.Run; if ExitCode = 0 then WriteLn('Compilation successful') else WriteLn('Compilation failed'); finally Process.Free; end; end. ``` ``` -------------------------------- ### PostgreSQL Connection Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/database-api-reference.md Shows how to connect to a PostgreSQL database using TSQLConnection. Set ConnectorType to 'postgresql' and specify the correct port. ```pascal var Conn: TSQLConnection; begin Conn := TSQLConnection.Create(nil); try Conn.ConnectorType := 'postgresql'; Conn.HostName := 'localhost'; Conn.DatabaseName := 'mydatabase'; Conn.UserName := 'postgres'; Conn.Password := 'password'; Conn.Port := 5432; Conn.Open; finally Conn.Close; Conn.Free; end; end. ``` -------------------------------- ### TStringList Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/classes-api-reference.md Demonstrates creating a TStringList, adding strings, associating objects with strings, and iterating through the list to display its contents. Remember to free the list and any associated objects. ```pascal var List: TStringList; I: Integer; begin List := TStringList.Create; try List.Add('First item'); List.Add('Second item'); List.Objects[0] := TObject.Create; WriteLn('Strings: '); for I := 0 to List.Count - 1 do WriteLn(' ', List[I]); // Iterate with objects for I := 0 to List.Count - 1 do if List.Objects[I] <> nil then WriteLn(List[I], ' has object'); finally List.Free; end; end. ``` -------------------------------- ### TJSONObject Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/fpjson-api-reference.md Demonstrates creating a TJSONObject with initial values, adding a new key-value pair, accessing values by type, and printing the formatted JSON. ```pascal var Person: TJSONObject; begin Person := TJSONObject.Create([ 'Name', 'Bob', 'Age', 35, 'Active', true ]); WriteLn(Person.Strings['Name']); // 'Bob' WriteLn(Person.Integers['Age']); // 35 Person.Add('Email', 'bob@example.com'); WriteLn(Person.FormatJSON(DefaultFormat, 2)); Person.Free; end. ``` -------------------------------- ### Setting ShowWindow Option Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/process-api-reference.md Demonstrates how to set the ShowWindow property of a TProcess instance to control its window's display state. Examples include hiding, maximizing, and minimizing the window. ```pascal Process.ShowWindow := swoHide; // Hidden window Process.ShowWindow := swoMaximize; // Fullscreen Process.ShowWindow := swoMinimize; // Taskbar only ``` -------------------------------- ### Simple Command Execution Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/process-api-reference.md Executes a given command and waits for it to complete, then prints the exit code. This is a basic example for running external executables. ```pascal procedure RunCommand(const Cmd: string); var Process: TProcess; begin Process := TProcess.Create(nil); try Process.Executable := Cmd; Process.Execute; Process.WaitOnExit; WriteLn('Exit code: ', Process.ExitCode); finally Process.Free; end; end; // Usage RunCommand('python script.py'); ``` -------------------------------- ### SQLite Connection Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/database-api-reference.md Illustrates connecting to an SQLite database file using TSQLConnection. Set ConnectorType to 'sqlite3' and provide the database file path. ```pascal var Conn: TSQLConnection; begin Conn := TSQLConnection.Create(nil); try Conn.ConnectorType := 'sqlite3'; Conn.DatabaseName := '/path/to/database.db'; Conn.Open; finally Conn.Close; Conn.Free; end; end. ``` -------------------------------- ### Verify FPC and fpdoc Installation Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/configuration-reference.md Shell commands to check the FPC compiler version and fpdoc tool availability, and verify the source directory. ```bash # Check FPC installation which fpc fpc -v # Check fpdoc fpdoc --help # Verify source location ls $FPCSRCDIR/rtl/ ls $FPCSRCDIR/packages/ ``` -------------------------------- ### TShowWindowOptions Enumeration Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/process-api-reference.md Enumerates options for controlling how a process's window is displayed when it starts. These options range from hiding the window to maximizing or minimizing it. ```pascal type TShowWindowOptions = ( swoHide, // Hide window swoMaximize, // Maximize window swoMinimize, // Minimize window swoRestore, // Restore from minimized/maximized swoShow, // Show window swoShowDefault, // Show as configured swoShowMaximized, // Show maximized swoShowMinimized, // Show minimized swoShowMinNoActive, // Show minimized, no focus swoShowNA, // Show no activate swoShowNormal // Show normal ); ``` -------------------------------- ### TTable Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/database-api-reference.md Shows how to use the TTable class to open a table, set index fields, and locate records. Suitable for direct record manipulation. ```pascal var Table: TTable; begin Table := TTable.Create(nil); try Table.DatabaseName := 'mydb'; Table.TableName := 'employees'; Table.IndexFieldNames := 'LastName,FirstName'; Table.Open; // Find employee if Table.Locate('EmployeeID', 5, []) then WriteLn('Found: ', Table.Fields['Name'].AsString); finally Table.Close; Table.Free; end; end. ``` -------------------------------- ### FPC Documentation XML Cross-Reference Links Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/configuration-reference.md Examples of using the tag for cross-references within FPC documentation XML. ```xml ``` -------------------------------- ### TStream Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/classes-api-reference.md Demonstrates basic usage of TStream descendants, including creating a TMemoryStream, writing data, resetting position, and reading data back. ```pascal // Note: TStream is abstract; use concrete descendants like TFileStream var Stream: TMemoryStream; Data: string; begin Stream := TMemoryStream.Create; try Data := 'Hello, Stream!'; Stream.Write(Data[1], Length(Data)); Stream.Position := 0; // Reset to beginning SetLength(Data, Stream.Size); Stream.ReadBuffer(Data[1], Stream.Size); WriteLn(Data); finally Stream.Free; end; end. ``` -------------------------------- ### TRequest Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/http-protocol-reference.md Demonstrates how to use the TRequest class to access request method, query parameters, cookies, and headers. Ensure TRequest is freed after use. ```pascal var Request: TRequest; begin Request := TRequest.Create; try // Check request method if Request.Method = 'GET' then WriteLn('Processing GET request'); // Get query parameters WriteLn('Search: ', Request.QueryFields['q']); // Get cookies WriteLn('Session: ', Request.GetCookie('PHPSESSID')); // Get headers WriteLn('Content-Type: ', Request.GetHeader('Content-Type')); finally Request.Free; end; end. ``` -------------------------------- ### Run Process Synchronously Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/process-api-reference.md Starts a process and waits for it to complete, returning its exit code. Useful for tasks that must finish before the application proceeds. ```pascal var Process: TProcess; ExitCode: Integer; begin Process := TProcess.Create(nil); try Process.Executable := 'gcc'; Process.Parameters.Add('-o'); Process.Parameters.Add('program'); Process.Parameters.Add('main.c'); ExitCode := Process.Run; if ExitCode = 0 then WriteLn('Compilation successful') else WriteLn('Compilation failed'); finally Process.Free; end; end. ``` -------------------------------- ### Pascal Method Signature Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/README.md Illustrates the full Pascal type signature for a method, including parameters with default values and the return type. This format is used in API reference documents. ```pascal function MethodName(Param1: Type1; Param2: Type2 = DefaultValue): ReturnType; virtual; ``` -------------------------------- ### TCollection Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/classes-api-reference.md Illustrates creating a TCollection, adding items of a specific class (TNamedItem), and accessing collection properties. Remember to free the collection instance. ```pascal type TNamedItem = class(TCollectionItem) FName: string; property Name: string read FName write FName; end; var Items: TCollection; Item: TCollectionItem; begin Items := TCollection.Create(TNamedItem); try Item := Items.Add; TNamedItem(Item).Name := 'First'; Item := Items.Add; TNamedItem(Item).Name := 'Second'; WriteLn('Total items: ', Items.Count); finally Items.Free; end; end. ``` -------------------------------- ### TSQLQuery Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/database-api-reference.md Demonstrates how to use TSQLQuery to execute both SELECT and INSERT statements with parameters. It shows creating a query, setting SQL and parameters, opening the query for SELECT, iterating through results, and executing an INSERT statement. ```pascal var Conn: TSQLConnection; Query: TSQLQuery; begin Conn := TSQLConnection.Create(nil); Conn.ConnectorType := 'mysql'; Conn.Open; try // SELECT query Query := Conn.CreateQuery as TSQLQuery; Query.SQL.Text := 'SELECT * FROM users WHERE status = :Status'; Query.Params.ParamByName('Status').AsString := 'active'; Query.Open; while not Query.Eof do begin WriteLn(Query.Fields['username'].AsString); Query.Next; end; Query.Close; Query.Free; // INSERT query Query := Conn.CreateQuery as TSQLQuery; Query.SQL.Text := 'INSERT INTO logs (msg, ts) VALUES (:Msg, :TS)'; Query.Params.ParamByName('Msg').AsString := 'Application started'; Query.Params.ParamByName('TS').AsDateTime := Now; Query.Execute; Query.Free; finally Conn.Close; Conn.Free; end; end. ``` -------------------------------- ### MS SQL Server Connection Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/database-api-reference.md Establishes a connection to an MS SQL Server database using TSQLConnection. Ensure the ConnectorType, HostName, DatabaseName, UserName, Password, and Port are correctly configured for your environment. ```pascal var Conn: TSQLConnection; begin Conn := TSQLConnection.Create(nil); try Conn.ConnectorType := 'mssql'; Conn.HostName := 'sql-server.example.com'; Conn.DatabaseName := 'mydatabase'; Conn.UserName := 'sa'; Conn.Password := 'password'; Conn.Port := 1433; Conn.Open; finally Conn.Close; Conn.Free; end; end. ``` -------------------------------- ### Standard FPC Program Structure Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/configuration-reference.md A typical Pascal program structure used in FPC documentation examples, including mode directives and common units. ```pascal program ExampleName; {$MODE ObjFpc}{$H+} uses SysUtils, Classes; var Variable: Type; begin // Implementation end. ``` -------------------------------- ### JSON Object Memory Management Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/fpjson-api-reference.md Illustrates how to manage memory for JSON objects, emphasizing that parent objects own and free their children. The example uses a try-finally block for safe deallocation. ```pascal var Root: TJSONObject; begin Root := TJSONObject.Create(['items', TJSONArray.Create([...])]); try // Use Root WriteLn(Root.FormatJSON()); finally Root.Free; // Frees Root and all descendants end; end. ``` -------------------------------- ### TJSONArray Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/fpjson-api-reference.md Demonstrates creating a TJSONArray with initial elements, accessing elements by index using type-specific properties, adding a null value, and formatting the array to a JSON string with indentation. ```pascal var Arr: TJSONArray; begin Arr := TJSONArray.Create([ TJSONString.Create('first'), TJSONIntegerNumber.Create(42), TJSONBoolean.Create(true) ]); WriteLn('Count: ', Arr.Count); // 3 WriteLn('Element 0: ', Arr.Strings[0]); // 'first' WriteLn('Element 1: ', Arr.Integers[1]); // 42 Arr.Add(TJSONNull.Create()); WriteLn(Arr.FormatJSON(DefaultFormat, 2)); Arr.Free; end. ``` -------------------------------- ### List Available Documentation Targets Source: https://github.com/fpc/fpcdocumentation/blob/main/README.md Run this command to see all possible output formats for the documentation. Requires GNU make. ```sh make help ``` -------------------------------- ### TProcess.WaitOnExit Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/process-api-reference.md Blocks execution until the process, previously started with `Execute()`, terminates. ```APIDOC ## TProcess.WaitOnExit ### Description Blocks until process terminates. Used after `Execute()`. ### Method `procedure WaitOnExit; ` ### Parameters None ### Returns None ### Usage ```pascal Process.Execute; Process.WaitOnExit; // Block until done WriteLn('Process finished with code: ', Process.ExitCode); ``` ``` -------------------------------- ### TCookie Usage Example Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/http-protocol-reference.md Illustrates how to create and configure a TCookie object, setting various attributes like name, value, expiration, and security flags. The AsString method formats the cookie for the Set-Cookie header. ```pascal var Cookie: TCookie; begin Cookie := TCookie.Create; try Cookie.Name := 'auth_token'; Cookie.Value := 'abc123def456'; Cookie.Path := '/'; Cookie.Domain := 'example.com'; Cookie.Expires := IncDay(Now, 7); // 7 days Cookie.Secure := True; // HTTPS only Cookie.HttpOnly := True; // No JavaScript access WriteLn(Cookie.AsString); // Output: auth_token=abc123def456; Path=/; Domain=example.com; ... finally Cookie.Free; end; end. ``` -------------------------------- ### Page Size Retrieval Source: https://github.com/fpc/fpcdocumentation/blob/main/examples/go32ex/go32.txt Function to get the size of a single memory page. ```APIDOC ## get_page_size : Longint ### Description Returns the size of a single memory page. ### Method N/A (Function) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example (* not my job *) ### Response #### Success Response - **Return Value** (Longint) - Size of a single page in bytes (typically 4096 bytes). #### Response Example (* not my job *) ``` -------------------------------- ### Build HTML with Custom CSS Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/configuration-reference.md Command-line instruction to build FPC HTML documentation using a custom CSS file. ```bash fpdoc --package fcl --input xml/*.xml \ --css custom.css --output html/ ``` -------------------------------- ### Build Single Module HTML Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/configuration-reference.md Command-line instruction to build HTML documentation for a single FPC module. ```bash fpdoc --package rtl --input xml/modulename.xml --output html/ ``` -------------------------------- ### Complete Element Declaration Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/configuration-reference.md Comprehensive XML structure for an element, including descriptions, examples, cross-references, version info, and errors. ```xml Brief description (one line).

Detailed description with context.

Multiple paragraphs for comprehensive documentation.

var X: Integer; begin X := SomeFunction(Value); WriteLn(X); end.
Availability information Description of error condition
``` -------------------------------- ### Build RTL Reference Documentation Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/configuration-reference.md Command to build the RTL reference documentation, specifying the FPC source directory. ```bash # Build RTL reference make rtl.chk FPCSRCDIR=/path/to/fpc/source ``` -------------------------------- ### Build Both RTL and FCL Reference Documentation Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/configuration-reference.md Command to build both RTL and FCL reference documentation, specifying the FPC source directory. ```bash # Build both make rtl.chk fcl.chk FPCSRCDIR=/path/to/fpc/source ``` -------------------------------- ### Get JSON Element Type Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/fpjson-api-reference.md Returns the JSON type constant for this data element. The base class returns jtUnknown. ```pascal function JSONType: TJSONtype; ``` -------------------------------- ### Get Segment Base Address Source: https://github.com/fpc/fpcdocumentation/blob/main/examples/go32ex/go32.txt Retrieves the 32-bit linear base address from the descriptor table for a given segment selector. ```pascal function get_segment_base_address (d : Word) : Longint; ``` -------------------------------- ### Object Creation and Management in Pascal Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/README.md Demonstrates the standard pattern for creating, using, and freeing objects in Pascal. Ensure objects are always freed using a try..finally block to prevent memory leaks. ```pascal var Obj: TClassName; begin Obj := TClassName.Create(Parameters); try // Use object finally Obj.Free; // Always free end; end; ``` -------------------------------- ### Build FCL Reference Documentation Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/configuration-reference.md Command to build the FCL reference documentation, specifying the FPC source directory. ```bash # Build FCL reference make fcl.chk FPCSRCDIR=/path/to/fpc/source ``` -------------------------------- ### Generate Standalone HTML Documentation Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/configuration-reference.md Command-line instruction to generate comprehensive standalone HTML documentation for all FPC units. ```bash fpdoc --all-units --quiet --output ~/docs/fpc --package rtl ``` -------------------------------- ### Wait for Process Completion Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/process-api-reference.md Blocks the current thread until a process started with `Execute` terminates. This is typically called after `Execute` to ensure the process has finished. ```pascal Process.Execute; Process.WaitOnExit; // Block until done WriteLn('Process finished with code: ', Process.ExitCode); ``` -------------------------------- ### FPC Documentation Build Targets Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/configuration-reference.md Lists common targets for building FPC documentation in various formats using make. ```makefile make help # List all available targets make dvi # Generate DVI format make html # Generate HTML format make ps # Generate PostScript make pdf # Generate PDF make txt # Generate plain text make chm # Generate CHM (Windows help) make rtl.chk # Build RTL reference only make fcl.chk # Build FCL reference only ``` -------------------------------- ### FPC Documentation Output Format Options Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/configuration-reference.md Command-line options for specifying the output format for FPC documentation generation. ```bash --format=html # Default HTML --format=chm # Compiled Help Module --format=txt # Plain text --format=ipf # OS/2 Information Presentation Facility ``` -------------------------------- ### FPC Build System Scripts Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/configuration-reference.md Common Make commands for managing the FPC documentation build process. ```bash # Complete release build ./fixdocs.sh # Generate all formats make all # Clean build artifacts make clean # Rebuild from scratch make distclean ``` -------------------------------- ### TCustomSession Class Definition Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/http-protocol-reference.md Defines the base class for session management, including methods for creating, setting, and getting session variables, and checking for expiration. ```pascal type TCustomSession = class(TComponent) constructor Create(AOwner: TComponent); override; function GetSessionVariable(const VarName: string): string; procedure SetSessionVariable(const VarName, AValue: string); function IsExpired: Boolean; end; ``` -------------------------------- ### Generate HTML Reference Documentation Source: https://github.com/fpc/fpcdocumentation/blob/main/README.md Builds the standard HTML reference documentation for the RTL and FCL components. The output will be in 'rtl' and 'fcl' subdirectories. ```sh make rtl.chk make fcl.chk ``` -------------------------------- ### Generate HTML Reference Documentation with Custom Source Path Source: https://github.com/fpc/fpcdocumentation/blob/main/README.md Generates only the RTL and FCL reference documentation in HTML format, specifying a custom location for the FPC source files. ```sh make rtl.chk fcl.chk FPCSRCDIR=/path/to/fpc/sources ``` -------------------------------- ### File Manipulation Functions Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/sysutils-api-reference.md Perform basic file operations such as deleting, renaming, and getting file size. Also includes functions to change the current directory. ```pascal function DeleteFile(FileName: string): Boolean; function RenameFile(OldName, NewName: string): Boolean; function FileSize(const FileName: string): Int64; procedure GetDir(DriveNr: Byte; var Dir: string); procedure ChDir(const Dir: string); ``` ```pascal if DeleteFile('temp.tmp') then WriteLn('File deleted'); if RenameFile('old.txt', 'new.txt') then WriteLn('File renamed'); Size := FileSize('large_file.bin'); WriteLn('File size: ', Size, ' bytes'); ``` -------------------------------- ### Exception Handling with Try..Except Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/sysutils-api-reference.md Demonstrates how to catch specific exception types like `EConvertError` and `EFileNotFound` using a `try..except` block. This allows for graceful error recovery. ```pascal try X := StrToInt('abc'); // Raises EConvertError except on E: EConvertError do WriteLn('Conversion error: ', E.Message); end; try F := FileOpen('missing.txt', fmOpenRead); except on E: EFileNotFound do WriteLn('File not found'); end; ``` -------------------------------- ### Specify Custom FPC Source Directory for HTML Source: https://github.com/fpc/fpcdocumentation/blob/main/README.md Builds HTML reference documentation while specifying a custom location for the FPC source files using the FPCSRCDIR make variable. ```sh make html FPCSRCDIR=/path/to/fpc/sources ``` -------------------------------- ### TJSONObject Get Method Overloads Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/fpjson-api-reference.md Retrieves a value associated with a key, with an option to provide a default value if the key is not found. Overloaded for TJSONData, string, and Integer return types. ```pascal function Get(const Key: string; const DefaultValue: TJSONData): TJSONData; function Get(const Key: string; const DefaultValue: string): string; function Get(const Key: string; const DefaultValue: Integer): Integer; ``` -------------------------------- ### Pascal String Validation Functions Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/exported-symbols.md These functions validate if a given string conforms to specific formats such as identifiers, email addresses, URLs, or GUIDs. They return a Boolean indicating validity. ```pascal function IsValidIdent(const Ident: string): Boolean; function IsValidEmail(const Email: string): Boolean; function IsValidURL(const URL: string): Boolean; function IsValidGUID(const GUID: string): Boolean; ``` -------------------------------- ### Help Configuration in fp.ini Source: https://github.com/fpc/fpcdocumentation/blob/main/README.md This INI file configuration shows how the textmode IDE stores the paths to CHM help files. Ensure these paths are correct for the IDE to locate the help documentation. ```ini [Help] Files="/fpc/fpcdocs/toc.chm;/fpc/fpcdocs/fcl.chm;/fpc/fpcdocs/ref.chm;/fpc/fpcdocs/rtl.chm;/fpc/fpcdocs/prog.chm;/fpc/fpcdocs/user.chm;/fpc/fpcdocs/fclres.chm" ``` -------------------------------- ### Get Next Selector Increment Value Source: https://github.com/fpc/fpcdocumentation/blob/main/examples/go32ex/go32.txt Returns the increment value used for calculating subsequent selectors when allocating multiple descriptors with allocate_ldt_descriptors. This is necessary because allocate_ldt_descriptors only returns the first selector. ```pascal function get_next_selector_increment_value : Word; ``` -------------------------------- ### Reading Process Output Line-by-Line Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/process-api-reference.md Executes an external command and captures its standard output, then processes it line by line. Ensure the 'find' command is available in your system's PATH. ```pascal var Process: TProcess; Lines: TStringList; Output: TMemoryStream; begin Process := TProcess.Create(nil); try Process.Executable := 'find'; Process.Parameters.Add('.'); Process.Parameters.Add('-name'); Process.Parameters.Add('*.pas'); Output := TMemoryStream.Create; Lines := TStringList.Create; try Process.Options := [poUsePipes]; Process.Output := Output; Process.Execute; Process.WaitOnExit; // Convert output to strings Output.Position := 0; Lines.LoadFromStream(Output); WriteLn('Found files:'); for I := 0 to Lines.Count - 1 do WriteLn(' ', Lines[I]); finally Lines.Free; Output.Free; end; finally Process.Free; end; end. ``` -------------------------------- ### Generate CHM (Windows Help) Documentation Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/configuration-reference.md Command to generate documentation in CHM format, setting the HTMLFMT variable. ```bash make html HTMLFMT=chm FPCSRCDIR=/path/to/fpc/source ``` -------------------------------- ### FCL Class Hierarchy Overview Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/module-index.md Presents a simplified view of the Free Component Library (FCL) class hierarchy, highlighting key base classes and their common descendants. ```text TObject ├── TComponent (classes) │ ├── TDataSet (db) │ │ ├── TQuery │ │ ├── TTable │ │ └── TDataModule │ ├── TDatabase (db) │ ├── THttpServer (httpprotocol) │ ├── TWebModule (fpweb) │ └── [other components] ├── TStream (classes) │ ├── TFileStream │ ├── TMemoryStream │ ├── THandleStream │ └── [other stream types] ├── TList (classes) │ ├── TObjectList (contnrs) │ └── TStringList (classes) ├── TJSONData (fpjson) │ ├── TJSONArray │ ├── TJSONObject │ ├── TJSONString │ └── [other JSON types] ├── TThread (systhrds) └── [other root types] ``` -------------------------------- ### Providing Input to a Process Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/process-api-reference.md Executes an external command ('sort') and provides input data via a stream. The sorted output is then read back into a string. Ensure the 'sort' command is available. ```pascal var Process: TProcess; Input: TMemoryStream; Output: TMemoryStream; begin Process := TProcess.Create(nil); try Process.Executable := 'sort'; Input := TMemoryStream.Create; Output := TMemoryStream.Create; try // Prepare input data Input.WriteBuffer('apple'#13#10'zebra'#13#10'mango'#13#10, 18); Input.Position := 0; Process.Options := [poUsePipes]; Process.Input := Input; Process.Output := Output; Process.Execute; Process.WaitOnExit; // Read sorted output Output.Position := 0; SetLength(Result, Output.Size); Output.ReadBuffer(Result[1], Output.Size); WriteLn('Sorted: ' + Result); finally Output.Free; Input.Free; end; finally Process.Free; end; end. ``` -------------------------------- ### Pascal Date Part Extraction Functions Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/exported-symbols.md Extracts specific components (day, month, year, hour, minute, second, millisecond) from a TDateTime value. Also provides functions to get just the date or time part. ```pascal function DayOf(const AValue: TDateTime): Word; function MonthOf(const AValue: TDateTime): Word; function YearOf(const AValue: TDateTime): Word; function HourOf(const AValue: TDateTime): Word; function MinuteOf(const AValue: TDateTime): Word; function SecondOf(const AValue: TDateTime): Word; function MilliSecondOf(const AValue: TDateTime): Word; function DateOf(const AValue: TDateTime): TDateTime; function TimeOf(const AValue: TDateTime): TDateTime; ``` -------------------------------- ### Generate IPF (OS/2 Help) Documentation Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/configuration-reference.md Command to generate documentation in IPF format, setting the HTMLFMT variable. ```bash make rtl.chk HTMLFMT=ipf FPCSRCDIR=/path/to/fpc/source ``` -------------------------------- ### FPC Mode Directives Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/configuration-reference.md Pascal code demonstrating common mode directives for FPC compilation. ```pascal {$MODE ObjFpc} // Object Pascal mode (recommended) {$MODE Delphi} // Delphi compatibility mode {$H+} // Long strings (modern) {$MODESWITCH ADVANCEDRECORDS} // Advanced record features ``` -------------------------------- ### Generate IPF Documentation for OS/2 Help Source: https://github.com/fpc/fpcdocumentation/blob/main/README.md Generates a single .ipf file for compilation into an OS/2 .INF help file. Specify the FPC source directory if it's not in the default location. ```sh make rtl.chk HTMLFMT=ipf FPCSRCDIR=/path/to/fpc/source ``` -------------------------------- ### File Operation Functions Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/exported-symbols.md Includes functions for deleting, renaming, creating, and managing directories, as well as path manipulation. ```Pascal function DeleteFile(FileName: string): Boolean; function RenameFile(OldName, NewName: string): Boolean; procedure GetDir(DriveNr: Byte; var Dir: string); procedure ChDir(const Dir: string); function MkDir(const Dir: string): Integer; function RmDir(const Dir: string): Integer; function GetCurrentDir: string; function SetCurrentDir(const Dir: string): Boolean; function ExpandFileName(const FileName: string): string; function ExtractFilePath(const FileName: string): string; function ExtractFileDir(const FileName: string): string; function ExtractFileDrive(const FileName: string): string; function ExtractFileName(const FileName: string): string; function ExtractFileExt(const FileName: string): string; function ExtractRelativePath(BaseName, FileName: string): string; function ChangeFileExt(const FileName, Extension: string): string; function FindFirst(const Path: string; Attr: Longint; var SearchRec: TSearchRec): Longint; function FindNext(var SearchRec: TSearchRec): Longint; procedure FindClose(var SearchRec: TSearchRec); ``` -------------------------------- ### Web Development Dependency Chain Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/module-index.md Illustrates the typical module dependencies for web development projects. Ensure these modules are available and correctly linked. ```text system → sysutils → classes → httpdefs → fphttp → fpweb ``` -------------------------------- ### TQuery Class Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/database-api-reference.md The TQuery class allows execution of SQL queries and retrieval of results. It provides properties to set the SQL command text and parameter values for parameterized queries. ```APIDOC ## TQuery Class ### Description Execute SQL queries and retrieve results. This class allows for parameterized queries and provides access to the results as a dataset. ### Properties - `SQL` (TStrings): SQL command text. - `Params` (TParams): Parameter values for parameterized queries. - `RequestLive` (Boolean): Get/set if result set is updatable. ### Usage Example ```pascal var Query: TQuery; begin Query := TQuery.Create(nil); try Query.DatabaseName := 'mydb'; Query.SQL.Text := 'SELECT * FROM users WHERE age > :MinAge ORDER BY name'; Query.Params.ParamByName('MinAge').AsInteger := 18; Query.Open; while not Query.Eof do begin WriteLn(Query.Fields['name'].AsString); Query.Next; end; finally Query.Close; Query.Free; end; end. ``` ``` -------------------------------- ### Collection Manipulation in Pascal Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/README.md Illustrates common operations for managing collections, including adding items, accessing items by index, and iterating through the collection. ```pascal List.Add(Item); List[Index]; for I := 0 to List.Count - 1 do DoSomething(List[I]); ``` -------------------------------- ### Stream Operations in Pascal Source: https://github.com/fpc/fpcdocumentation/blob/main/_autodocs/README.md Shows basic operations for working with streams, such as setting the position, reading data, and writing data. ```pascal Stream.Position := 0; Stream.Read(Buffer, Count); Stream.Write(Buffer, Count); ```