The Algol-24 Library Reference
Every routine and constant the library offers, alphabetically, after the pattern of Turbo Pascal's own reference: what it does, how it is declared, what is worth knowing about it, what else to look at, and a program that uses it.
Every example in this file has been run, and the output shown beneath it is what it printed.
Each example assumes the unit is reachable — run from the directory holding the .a24 files, or from one beside them.
Index
Abs | function | math |
Aliases | convention | graph and crt |
AppendAll | procedure | file |
AppendFile | class | file |
Arc | procedure, alias | graph |
ArcCoords | class | graph |
ArcTan | function | math |
AssertNear | procedure | testing |
At UtcAt | functions | time |
Bar | procedure, alias | graph |
Bar3D | procedure, alias | graph |
Black … White | constants | graph and crt |
Blink | constant | graph and crt |
CellWidth CellHeight | functions | graph |
Circle | procedure, alias | graph |
Clear | method | graph and crt |
ClearViewPort | procedure, alias | graph |
CloseCrt | procedure | crt |
CloseGraph | procedure | graph |
CloseSound | procedure | sound |
ClrEol | procedure | graph and crt |
ClrScr | procedure | graph and crt |
CopyFile | procedure | file |
CopyPut … TransparentPut | constants | graph |
Cos | function | math |
Crt | unit | crt |
DateTime | class | time |
Delay | procedure | crt and graph |
Delete | extension function | strings |
DelLine InsLine | procedures | graph and crt |
Describe | extension function | reflect |
Directory | class | file |
DisableMouse | procedure | graph and crt |
DiskFree DiskSize | functions | dos |
DrawPoly | procedure, alias | graph |
Ellipse | procedure, alias | graph |
EnableMouse | procedures and functions | graph and crt |
Entries | function | file |
Environment EnvName EnvValue | functions | dos |
Erase | procedure | file |
Event | class | graph and crt |
EventKinds | constants | graph and crt |
Exec | function | dos |
Exists | function | file |
Exp | function | math |
FileSize | function | file |
FillEllipse | procedure, alias | graph |
FillPoly | procedure, alias | graph |
FillSettings LineSettings | classes | graph |
FillStyles | constants | graph |
FloodFill | procedure, alias | graph |
Frac | function | math |
FreeSound | procedure | sound |
GetArcCoords | function, alias | graph |
GetAspectRatio | function | graph |
GetColor | function, alias | graph |
GetEnv HasEnv | functions | dos |
GetFillColor | function | graph |
GetFillPattern | function, alias | graph |
GetFillSettings GetLineSettings | functions, aliases | graph |
GetFillStyle | function | graph |
GetImage PutImage | function and procedure, aliases | graph |
GetMaxX | function | graph |
GetMaxY | function | graph |
GetPalette | method | graph and crt |
GetPixel | function, alias | graph |
GetTextSettings GetViewSettings | functions, aliases | graph |
GetX | function, alias | graph |
GetY | function, alias | graph |
GotoXY | procedure | graph and crt |
GraphDefaults | procedure, alias | graph |
HighVideo | procedure | graph and crt |
Image | class | graph |
ImageSize | function | graph |
InFile | class | file |
Infinity | constant | math |
InitCrt | procedures | crt |
InitGraph | procedure | graph |
Insert | extension function | strings |
InstallUserFont | procedure | graph |
Int | function | math |
IsDaylightSaving | function | time |
IsDirectory | function | file |
IsInfinite | function | math |
IsNaN | function | math |
IsTerminal | function | crt |
Join | extension function | strings |
KeyPressed | function | graph and crt |
KeyUp … KeyClose | constants | graph and crt |
LeftText … TopText | constants | graph |
Line | procedure, alias | graph |
LineRel | procedure, alias | graph |
LineTo | procedure, alias | graph |
Ln | function | math |
LoadSound | functions and procedures | sound |
Lower | extension function | strings |
LowVideo | procedure | graph and crt |
Max | function | math |
Min | function | math |
MouseButtons | function | graph and crt |
MouseEnabled | function | graph and crt |
MouseX | function | graph and crt |
MouseY | function | graph and crt |
MoveTo | procedure, alias | graph and crt |
NaN | constant | math |
NormVideo | procedure | graph and crt |
Now UtcNow | functions | time |
Odd | function | math |
OutFile | class | file |
OutText | procedure | graph |
OutTextXY | procedure | graph |
PathParts | class | file |
PenRel | procedure, alias | graph |
PenTo | procedure, alias | graph |
Pi | constant | math |
PieSlice | procedure, alias | graph |
Play | procedure and function | sound |
PlaySound | function | sound |
PollEvent | function | graph and crt |
PutPixel | procedure, alias | graph |
Random | function | random |
RandomInteger | function | random |
Randomize | procedure | random |
RandomReal | function | random |
ReadAll | functions and procedures | file |
ReadEvent | functions | graph and crt |
ReadKey | function | graph and crt |
ReadLines | function and procedure | file |
RecordFile | class | file |
Rectangle | procedure, alias | graph |
Rename | procedure | file |
Repeat | extension function | strings |
Replace | extension function | strings |
Round | function | math |
SameContent | extension function | reflect |
Score | function | sound |
ScreenHeight | function | graph |
ScreenWidth | function | graph |
Sector | procedure, alias | graph |
SetAspectRatio | procedure | graph |
SetBkColor GetBkColor | procedures, aliases | graph |
SetBlinkRate | procedure | graph |
SetColor | procedure, alias | graph |
SetFillPattern | procedure | graph |
SetFillStyle | procedures, aliases | graph |
SetLineStyle | procedure, alias | graph |
SetPalette | procedures | graph and crt |
SetSeed | procedure | random |
SetTextJustify | procedure, alias | graph |
SetTextStyle | method | graph |
SetUserCharSize | procedure, alias | graph |
SetVolume | procedure | sound |
SetWriteMode GetWriteMode | procedures, aliases | graph |
Show | procedure, alias | graph and crt |
Sin | function | math |
SolidLn … ThickWidth | constants | graph |
Sound | procedures | sound |
SoundAvailable | function | sound |
SoundLength | function | sound |
SoundPlaying | function | sound |
Split | extension function | strings |
SplitPath FullPath | functions | file |
Sqr | function | math |
Sqrt | function | math |
StopSounds | procedure | sound |
SurfaceAt | function | graph and crt |
TextBackground | procedure | graph and crt |
TextColor | procedure | graph and crt |
TextCols | function | graph and crt |
TextMode | procedure | graph |
TextRows | function | graph and crt |
TextSettings ViewSettings | classes | graph |
TextWidth TextHeight | functions | graph |
Trim | extension function | strings |
Trunc | function | math |
Upper | extension function | strings |
UtcOffset | function | time |
ViewPort | class | graph |
WhereX | function | graph and crt |
WhereY | function | graph and crt |
Window | class | graph and crt |
Write WriteLn | procedures | graph and crt |
WriteAll | procedure | file |
WriteLines | procedure | file |
Written | function | graph |
Abs
function — unit math
Function
Returns the absolute value of its argument.
Declaration
function Abs (X);
Remarks
X is an Integer or a Double, and the result has the same type as X. That follows from 0 - X taking its type from its operand rather than from anything this routine arranges, which is also why the function is written untyped.
Because an Integer is unbounded, the negation cannot overflow. Abs of −2¹²⁷ answers 2¹²⁷, where C's abs(INT_MIN) is undefined behavior.
Negative zero is normalized: Abs (-0.0) is 0.0, not -0.0. The comparison is <= rather than < for exactly this reason — -0.0 < 0 is false, so < would hand -0.0 straight back.
Being untyped, the result cannot initialize a variable of a written type: var N : Integer := Abs (-5); is refused, while var N := Abs (-5);, Abs (-5) + 1 and Take (Abs (-5)) are all accepted.
Raises Operands must be numbers. for an argument the subtraction cannot take, including a String and nil.
See also
Example
uses math;
WriteLn (Abs (-42));
WriteLn (Abs (-2.5));
WriteLn (Abs (-170141183460469231731687303715884105728));
Shell
42
2.5
170141183460469231731687303715884105728
Aliases
a convention — unit graph and crt
Function
Every surface method is also a free function taking the surface first.
Declaration
GotoXY (W, 3, 2) is W.GotoXY (3, 2)
Line (V, 1, 1, 40, 20) is V.Line (1, 1, 40, 20)
Remarks
crt follows the same convention with the same spellings, for the text verbs it shares.
Verb-first is how a Turbo Pascal program reads, and this library's vocabulary is Turbo Pascal's — so each of the seventy surface methods has a free-function twin. Each is a one-line delegate adding no behavior whatever, and each has its own entry in this reference, marked alias of the method it reaches.
They work on arity: GotoXY (Col, Row) is the screen and GotoXY (W, Col, Row) is that window. Before 0.1.4 every such call warned at its site; the compiler now settles a choice on arity when arity is enough, silently.
Two are shaped around the language rather than declared twice:
⚠️ Write and WriteLn are one variadic each, inspecting their first value — a leading Window is the surface written to, not a value written. A variadic already matches every arity, so a second declaration could only be ambiguous against it.
⚠️ MoveTo takes an untyped surface and asks what it is. Two declarations of one arity would put the choice back on the argument's type, which a gradual type system settles at run time and warns about — correctly.
The screen-wide verbs are untouched: a bare Write still means the screen, and System.Write still means the console.
See also
Example
See any alias entry — Line, GotoXY, SetColor — or examples/ide.a24, which uses both spellings.
AppendFile
class — unit file
Function
A file open for writing at the end, keeping what is already there.
Declaration
constructor AppendFile (Path : String);
// every OutFile member, inherited: Write, WriteLine, WriteBytes,
// Flush, Position, Size, Close
procedure Seek (Offset : Integer) refused -- see below
Remarks
Everything OutFile does, opened differently — which is the whole of the difference, so it inherits rather than restating five methods.
This is Turbo Pascal's Append to OutFile's Rewrite. A file that does not exist yet is created, so appending to nothing is not an error.
⚠️ Seek is refused here rather than ignored. A file opened for appending writes at the end whatever its position says — the operating system's rule, not this unit's — so a Seek would appear to work and then change nothing. It raises Seek: an AppendFile always writes at the end. Use OutFile where writing to a position matters.
Raises AppendFile: cannot open '<Path>'. when the file cannot be opened for appending.
See also
Example
uses file;
WriteAll ('diary.txt', 'monday' + #10);
var A := AppendFile ('diary.txt');
A.WriteLine ('tuesday');
A.Close ();
WriteLn (ReadAll ('diary.txt'));
Erase ('diary.txt');
Shell
monday
tuesday
Arc
procedure, alias of ViewPort.Arc — unit graph
Function
Draws a circular arc on a viewport.
Declaration
procedure Arc (V : ViewPort, X : Integer, Y : Integer, StartAngle : Integer,
EndAngle : Integer, Radius : Integer);
Remarks
An alias of the method: Arc (V, …) is V.Arc (…).
Angles are degrees, zero at three o'clock, counting counterclockwise — Turbo Pascal's convention, and the one Arc (V, 100, 100, 0, 90, 50) reads as: a quarter turn upward.
⚠️ Counterclockwise on a screen means Y gets smaller. A screen's Y grows downward, so the four cardinal angles land like this:
| angle | where | |
|---|---|---|
| 0° | three o'clock | X + R, Y |
| 90° | twelve o'clock | X, Y − R |
| 180° | nine o'clock | X − R, Y |
| 270° | six o'clock | X, Y + R |
Getting that sign backwards mirrors every curve in the library, and nothing but a picture would catch it — which is why the tests assert all four.
The sweep runs from StartAngle to EndAngle the counterclockwise way, so Arc (V, X, Y, 350, 10, R) is the twenty degrees across three o'clock rather than the three hundred and forty the other way round. Equal angles draw a point; 0, 360 is the whole circle.
Drawn in the pen's color, patterned by the current line style, and thickened along the radius — the only direction that keeps a thick arc the same shape.
⚠️ The pen is not moved. An arc is a figure, not a journey, so a following LineTo still draws from wherever the pen was.
Raises Arc needs a radius of zero or more. and CloseGraph has closed this surface.
See also
GetArcCoords, Line, SetColor, SetLineStyle, ViewPort
Example
uses graph;
InitGraph (640, 480, 'arc', False);
var V := ViewPort (100, 60, 300, 300, 1);
// A full circle, then a quarter of one drawn thick over it.
SetColor (V, LightGray);
Arc (V, 150, 150, 0, 360, 100);
SetColor (V, Yellow);
SetLineStyle (V, SolidLn, 0, ThickWidth);
Arc (V, 150, 150, 0, 90, 100);
Show (V);
// Ninety degrees is twelve o'clock: a SMALLER Y than the center.
System.WriteLn (V.Buf.GetInt ((49 * 300 + 149) * 4) <> 0);
System.WriteLn (V.Buf.GetInt ((149 * 300 + 149) * 4) = 0);
CloseGraph ();
Shell
true
true
ArcCoords
class — unit graph
Function
Where the last arc on a surface was centered, began and ended.
Declaration
constructor ArcCoords (X : Integer, Y : Integer, XStart : Integer,
YStart : Integer, XEnd : Integer, YEnd : Integer);
// readable
X, Y : Integer the center the arc was drawn about
XStart, YStart : Integer where the curve began
XEnd, YEnd : Integer where it ended
Remarks
Turbo Pascal's ArcCoordsType, with its six field names kept whole so a program written to them still reads.
⚠️ It is answered, not filled in. Turbo Pascal's GetArcCoords took a var record and wrote into it; GetArcCoords here returns one of these. That is the same record with the awkward half of Pascal's calling convention left out — there is nothing to declare before the call, and nothing to leave uninitialized if the call is skipped.
⚠️ The six are a snapshot. A later arc makes a new ArcCoords rather than changing an existing one, so a value held on to still describes the figure it came from.
Constructing one directly is legal and occasionally useful — for stashing the geometry of a figure drawn some other way — but the usual source is GetArcCoords.
See also
Example
See GetArcCoords.
ArcTan
function — unit math
Function
Returns the arctangent of its argument, in radians.
Declaration
function ArcTan (X : Double) : Double;
Remarks
The result lies between −π/2 and π/2. ArcTan is an odd function, so negating the argument negates the result.
It is a foreign declaration onto libm's atan, which is the whole of the implementation.
There is no two-argument form, so a full-circle angle is not available from this routine alone.
See also
Example
Four times the arctangent of one is π — the classic way of arriving at it.
uses math;
WriteLn (ArcTan (1.0) * 4);
WriteLn (ArcTan (0.0));
Shell
3.141592653589793
0.0
AssertNear
procedure — unit testing
Function
Fails a test unless two Doubles agree to within a tolerance.
Declaration
procedure AssertNear (Expected : Double, Actual : Double, Tolerance : Double);
Remarks
For a floating-point result whose exact bits are not guaranteed. IEEE 754 requires the arithmetic operations and Sqrt to be correctly rounded, so those can and should be asserted exactly with AssertEqual; it requires nothing of Sin, Cos, Exp, Ln and ArcTan, whose last bit may differ between one platform's libm and another's. Those are what this is for.
The tolerance is inclusive, and the comparison is symmetric in the first two arguments. A tolerance of zero asks for exact agreement, which is a clearer way of saying so than AssertEqual when the values are Doubles.
⚠️ NaN always fails, in either position. Every comparison against NaN is false, so a test written with > would let one through — a routine that answered NaN did not land near anything. The infinities fail too, unless the tolerance is itself infinite.
⚠️ Only usable inside a test block, under algc --test. It reports through the built-in Fail, which does not exist in an ordinary program: calling AssertNear outside a test answers Undefined variable 'Fail'.
A failure reads Failed. Expected 1.22 to within 0.001 but got 1.5. — Fail supplies the first word.
The unit deliberately depends on nothing, math included, so that math's own tests may use it without the two importing one another.
See also
Example
uses testing;
test 'A measurement lands where it should';
begin
AssertNear (1.22, 1.2201, 0.001);
AssertNear (3.14159, 3.14160, 0.001);
end
Shell
[INFO] Test: A measurement lands where it should .................... [ PASS ]
At
functions — unit time
Function
Return the moment a given epoch names, as a DateTime.
Declaration
function At (Epoch : Double) : DateTime;
function UtcAt (Epoch : Double) : DateTime;
Remarks
What makes clock () usable. The language hands out seconds since the epoch as a Double and stops there; these read that number as a date. A moment recorded earlier, or one arrived at by arithmetic, goes through here.
At reads it in the host's own time zone and UtcAt without a zone. Both answer the same instant — the Epoch field is identical — and only the calendar fields differ.
A local reading is by definition the UTC reading of the instant shifted by the zone's offset, so At (E).Text () and UtcAt (E + UtcOffset (E)).Text () always agree. That identity is how the unit tests itself in a way that holds in every zone.
Raises time: the host could not break down that moment. for an epoch outside the host's representable range, which a value far beyond the year 9999 reaches.
See also
Example
uses time;
// A fixed epoch, so the answer is the same on every host.
var M := UtcAt (1234567890.0);
WriteLn (M.Year, '-', M.Month, '-', M.Day);
WriteLn (M.Hour, ':', M.Minute, ':', M.Second);
WriteLn (M.Text ());
// The fraction the calendar fields discard is still on the object.
WriteLn (UtcAt (1234567890.75).Epoch);
Shell
2009-2-13
23:31:30
2009-02-13 23:31:30
1.23456789075E9
Bar
procedure, alias of ViewPort.Bar — unit graph
Function
Fills a rectangle with the current fill pattern and color.
Declaration
procedure Bar (V : ViewPort, X1 : Integer, Y1 : Integer, X2 : Integer, Y2 : Integer);
Remarks
An alias of the method: Bar (V, …) is V.Bar (…).
The corners may be given either way round.
⚠️ No outline is drawn. Turbo Pascal's Bar is the fill alone, so a bordered bar is a Bar and a Rectangle over it — which is also how it gets two different colors, the fill pen and the drawing pen being separate. See SetFillStyle.
The pattern is tiled from the surface's origin rather than the bar's, so bars side by side share one weave. EmptyFill paints nothing at all, leaving what is beneath showing through.
The pen is not moved, a bar being a figure rather than a journey.
⚠️ This one is drawn by C, uniquely among the figures so far. A 300 × 200 bar is sixty thousand pixels and the interpreted loop measured 7.5 seconds; the same fill through alg_fill_rect is free — fifty full-surface bars cost what one does. The unit still decides everything that is a decision: which rectangle, which way round its corners came, which pattern, which color, and whether the fill is empty at all. What went to C is the run.
Raises CloseGraph has closed this surface. once the window has gone.
See also
FillStyles, Rectangle, SetFillStyle
Example
uses graph;
InitGraph (640, 480, 'bar', False);
var V := ViewPort (60, 60, 400, 260, 1);
// A chart's bars, each filled and then outlined -- two colors, because the
// fill pen and the drawing pen are separate.
var Heights := [180, 120, 210, 90, 150];
SetColor (V, White);
for var I := 0; I < 5; I := I + 1 do
begin
var Left := 30 + I * 70;
SetFillStyle (V, [SolidFill, HatchFill, XHatchFill,
InterleaveFill, SlashFill][I], LightGreen);
Bar (V, Left, 240 - Heights[I], Left + 50, 240);
Rectangle (V, Left, 240 - Heights[I], Left + 50, 240);
end
Show (V);
System.WriteLn (GetFillColor (V) = LightGreen);
System.WriteLn (GetColor (V) = White);
CloseGraph ();
Shell
true
true
Bar3D
procedure, alias of ViewPort.Bar3D — unit graph
Function
Fills a bar and draws it in three dimensions.
Declaration
procedure Bar3D (V : ViewPort, X1 : Integer, Y1 : Integer, X2 : Integer,
Y2 : Integer, Depth : Integer, Top : Boolean);
Remarks
An alias of the method: Bar3D (V, …) is V.Bar3D (…).
The front face is filled with the current fill pattern and outlined with the current line style and pen — Bar and Rectangle in one call, which is what Turbo Pascal's Bar3D was. Depth then projects it up and to the right at forty-five degrees, drawing the right face and, when Top is true, the top one.
⚠️ Top exists for stacking. A column of bars wants the cap on the topmost alone; drawn with Top false, the ones beneath get their right face but no lid cutting across the stack. The right face is always drawn — it is what makes the bar look solid.
⚠️ Only the front face carries the pattern. The other faces are outlines, which is what keeps a patterned bar legible in three dimensions.
Turbo Pascal suggested a Depth of a quarter the bar's width, which still reads well. A depth of zero is exactly a Bar with a Rectangle over it — there is a test asserting the two are pixel-identical.
The pen is not moved: a figure is not a journey, which is the rule Arc, Circle, Bar and Rectangle keep as well. Only Line, LineTo and LineRel move it, because moving it is what they are for.
Raises Bar3D needs a depth of zero or more. and CloseGraph has closed this surface.
See also
Example
uses graph;
InitGraph (640, 480, 'bar3d', False);
var V := ViewPort (60, 60, 420, 280, 1);
// A row of solid bars, each capped -- the depth is a quarter of the width,
// which is what Turbo Pascal suggested and still reads well.
var Heights := [180, 120, 210, 90];
SetColor (V, White);
for var I := 0; I < 4; I := I + 1 do
begin
var Left := 40 + I * 90;
SetFillStyle (V, [SolidFill, HatchFill, SlashFill, XHatchFill][I], LightCyan);
Bar3D (V, Left, 250 - Heights[I], Left + 60, 250, 15, True);
end
// And a stack: only the topmost is capped, so no lid cuts across it.
SetFillStyle (V, SolidFill, LightRed);
Bar3D (V, 380, 190, 400, 250, 12, False);
Bar3D (V, 380, 130, 400, 190, 12, True);
Show (V);
System.WriteLn (GetX (V));
System.WriteLn (GetColor (V) = White);
CloseGraph ();
Shell
1
true
Blink
constant — unit graph and crt
Function
The blink flag, added onto a TextColor.
Declaration
const Blink := 16777216;
Remarks
In crt the terminal owns the cadence rather than this library, which is why that unit has no SetBlinkRate. Some terminals ignore blinking altogether, and no unit can make them do otherwise.
TextColor (LightRed + Blink) makes the ink blink — 267 milliseconds on, 267 off by default, the VGA's own cadence of sixteen frames each way; SetBlinkRate chooses another. The flag is per-color, as Turbo Pascal's was: the next TextColor without it writes steady text, and a steady stamp over a blinking cell ends its blinking. NormVideo and TextMode end it too.
Only the letters vanish; the cell's background stays, exactly as the adapter had it.
Turbo Pascal's value was 128 — the CGA attribute byte's bit 7, the same bit BASIC's COLOR 16 and up wrote. Here 128 is a legitimate navy, so the flag rides bit 24 and the spelling survives unchanged.
The phase advances whenever something presents, on the language's own clock (). A program drawing or sitting in a loop that ticks Write ('') blinks; one that draws once and halts shows whichever phase it landed in.
See also
Example
uses graph;
InitGraph (640, 480, 'blink', False);
TextColor (LightRed + Blink);
Write ('this text blinks');
NormVideo ();
WriteLn (' and this does not');
System.WriteLn (WhereY ());
CloseGraph ();
Shell
2
CellWidth
functions — unit graph
Function
The size of one text cell, in the logical space surfaces live in.
Declaration
function CellWidth () : Integer;
function CellHeight () : Integer;
Remarks
Cells are half as wide as they are tall — 16 × 32 for the shipped font — and a wide (CJK) glyph takes two of them.
⚠️ Both surface kinds share one logical space, and these are its ruler. A Window is placed in cells and a ViewPort in that space's pixels, so cell Col, Row begins at (Col - 1) * CellWidth (), (Row - 1) * CellHeight () — which is exactly what Window.PixelLeft and PixelTop answer. A viewport placed there stays there at every window size, because the whole space scales to the physical window as one.
The physical window's own pixels are a different ruler: GetMaxX measures those, and the background that the global OutTextXY draws on lives in them.
An InstallUserFont of a different cell size changes both answers.
See also
Example
uses graph;
InitGraph (640, 480, 'cells', False);
var W := Window (4, 5, 38, 20, 1);
// A chart one cell inside the window's frame, in the same logical space.
var Chart := ViewPort (W.PixelLeft () + CellWidth (),
W.PixelTop () + CellHeight (),
(W.Cols - 2) * CellWidth (),
(W.Rows - 2) * CellHeight (), 2);
System.WriteLn (CellWidth ());
System.WriteLn (CellHeight ());
System.WriteLn (Chart.X);
System.WriteLn (Chart.Y);
CloseGraph ();
Shell
16
32
64
160
Circle
procedure, alias of ViewPort.Circle — unit graph
Function
Draws a circle on a viewport.
Declaration
procedure Circle (V : ViewPort, X : Integer, Y : Integer, Radius : Integer);
Remarks
An alias of the method: Circle (V, …) is V.Circle (…).
Arc swept the whole way round, and everything said there holds — the pen's color, the line style's pattern, thickness spreading along the radius, and the pen left where it was.
The outline only. A filled disc waits on the figures that take a fill; SetFillStyle is the state they will use.
Raises Circle needs a radius of zero or more. and CloseGraph has closed this surface.
See also
Arc, Ellipse, GetArcCoords, GetAspectRatio, SetFillStyle, SetLineStyle
Example
uses graph;
InitGraph (640, 480, 'circle', False);
var V := ViewPort (100, 60, 300, 300, 1);
SetColor (V, LightCyan);
Circle (V, 150, 150, 120);
SetColor (V, Yellow);
SetLineStyle (V, DottedLn, 0, ThickWidth);
Circle (V, 150, 150, 60);
Show (V);
// Three o'clock on the outer circle is lit; the middle is hollow.
System.WriteLn (V.Buf.GetInt ((149 * 300 + 269) * 4) <> 0);
System.WriteLn (V.Buf.GetInt ((149 * 300 + 149) * 4) = 0);
CloseGraph ();
Shell
true
true
Clear
method of Window and ViewPort — unit graph and crt
Function
Clears a surface, whichever kind it is.
Declaration
procedure Clear (); // on a Window, and on a ViewPort
Remarks
crt has the same verb on its Window, aliased ClrScr, and no ClearViewPort — there being no viewports.
The one clearing verb both kinds of surface answer to. Turbo Pascal had two unrelated names for it — ClrScr in Crt and ClearViewPort in Graph — because text and pixels were different worlds there. They are one world here, so the verb is one verb, and the Turbo Pascal names are kept as aliases: ClrScr (W) and ClearViewPort (V).
⚠️ What a surface is cleared to differs, and follows the one rule. A grid is text, so its cells take the current TextBackground; a canvas is a graphic, so it goes back to the Transparent it was born as and whatever lies beneath shows through again.
That difference is the point rather than an inconsistency: painting a viewport black would hide what is under it, which is the opposite of clearing it. Filling one with a color is Bar over the whole of it.
The cursor, or the pen and the free-text position, go home to 1, 1.
⚠️ The settings are not touched. TextColor and TextBackground on a window; SetColor, SetLineStyle and SetFillStyle on a viewport. This clears the surface, not what you drew it with — a redraw after a clear should not have to say everything over again.
Every other surface is left alone, as ever.
Raises CloseGraph has closed this surface. once the window has gone.
See also
Bar, ClearViewPort, ClrEol, ClrScr, ViewPort, Window
Example
See ClearViewPort.
ClearViewPort
procedure, alias of ViewPort.Clear — unit graph
Function
Clears a viewport back to transparent.
Declaration
procedure ClearViewPort (V : ViewPort);
Remarks
An alias of the method: ClearViewPort (V) is V.Clear (). Turbo Pascal's name for it, kept; Clear is the verb.
⚠️ It erases rather than paints. The pixels go back to Transparent, so what lies beneath the viewport shows through again. There is no color to pass, because a cleared surface and a surface painted a color are different things — Bar over the whole viewport is the second one.
Turbo Pascal cleared to the background color, having no transparency to go back to. A stack of surfaces does, and transparent is what a fresh viewport already is, so this returns one to how it looked when made.
The pen and the free-text position go home to 1, 1, as a window's cursor does under ClrScr. The pen's color, the line style and the fill style are left alone.
Raises CloseGraph has closed this surface. once the window has gone.
See also
Example
uses graph;
InitGraph (640, 480, 'clear', False);
var V := ViewPort (50, 50, 120, 80, 1);
SetFillStyle (V, SolidFill, Red);
Bar (V, 1, 1, 120, 80);
PenTo (V, 40, 60);
System.WriteLn ('painted: ', GetPixel (V, 60, 40) = Red);
ClearViewPort (V);
// Back to transparent, not to a color -- so whatever lies beneath a viewport
// shows through it again.
System.WriteLn ('cleared: ', GetPixel (V, 60, 40) = Transparent);
// The pen goes home, as a window's cursor does; what the pen was set to does
// not change.
System.WriteLn ('pen home: ', GetX (V), ' ', GetY (V));
System.WriteLn ('fill kept: ', GetFillStyle (V) = SolidFill);
CloseGraph ();
Shell
painted: true
cleared: true
pen home: 1 1
fill kept: true
CloseGraph
procedure — unit graph
Function
Closes the graphics window.
Declaration
procedure CloseGraph ();
Remarks
Total: closing when nothing is open does nothing, so a handler or a test may call it unconditionally to reach a known state. The window may be reopened afterward with InitGraph.
Only the window and its renderer are released. SDL's video subsystem stays up for the life of the process, which is why ScreenWidth still answers after a close.
See also
Example
uses graph;
CloseGraph (); // nothing open: does nothing
InitGraph (320, 200, 'brief', False);
CloseGraph ();
CloseGraph (); // already closed: does nothing
System.WriteLn ('closed without complaint');
Shell
closed without complaint
ClrEol
procedure — unit graph and crt
Function
Clears the grid from the cursor to the end of its row.
Declaration
procedure ClrEol (); // the screen
procedure ClrEol (W : Window); // that window
Remarks
ClrEol (W) is an alias of W.ClrEol, clearing that window's row instead of the screen's.
The cleared cells take the current TextBackground, and the cursor does not move.
⚠️ Only the grid is touched. A graphic beneath the cleared cells — a chart a window was sitting on — shows through, intact. Erasing a graphic is a graphics act; this is a text verb, and text verbs act on text. That is the design's one rule, and this routine is where it is most visible.
Raises Graph is not open. without a window.
See also
Example
uses graph;
InitGraph (320, 200, 'eol', False);
Write ('doomed text');
GotoXY (1, 1);
ClrEol ();
System.WriteLn (WhereX ());
CloseGraph ();
Shell
1
ClrScr
procedure — unit graph and crt
Function
Clears the whole grid and homes the cursor.
Declaration
procedure ClrScr (); // the screen
procedure ClrScr (W : Window); // that window
Remarks
ClrScr (W) is an alias of W.Clear, clearing that window alone. Clear is the verb both kinds of surface answer to; ClrScr is Turbo Pascal's name for it on a grid, and ClearViewPort is Turbo Pascal's name for it on a canvas.
The bare ClrScr () is the base console layer — the root grid at Order 0 — and clears nothing else in the stack.
Every cell takes the current TextBackground — TextBackground (Blue); ClrScr; is how a classic screen paints its field in two lines. With the background Transparent the grid becomes wholly invisible and everything beneath shows.
Graphics are not touched, on the same rule as ClrEol.
Raises Graph is not open. without a window.
See also
Clear, ClearViewPort, ClrEol, TextBackground
Example
uses graph;
InitGraph (320, 200, 'scr', False);
GotoXY (5, 3);
TextBackground (Blue);
ClrScr ();
System.WriteLn (WhereX ());
System.WriteLn (WhereY ());
CloseGraph ();
Shell
1
1
Colors
constants — unit graph and crt
Function
The sixteen colors of a CGA text screen, and Transparent.
Declaration
const Black := 0; const DarkGray := 5592405;
const Blue := 170; const LightBlue := 5592575;
const Green := 43520; const LightGreen := 5635925;
const Cyan := 43690; const LightCyan := 5636095;
const Red := 11141120; const LightRed := 16733525;
const Magenta := 11141290; const LightMagenta := 16733695;
const Brown := 11162880; const Yellow := 16777045;
const LightGray := 11184810; const White := 16777215;
const Transparent := -1;
Remarks
crt declares the same sixteen values and sends them to the terminal as 24-bit color where it says it can, and as the nearest of the 256-color cube where it does not. See Crt.
Named 24-bit values, so TextColor (Yellow) reads like 1989 while being RGB underneath — and any other RGB Integer is just as welcome wherever these are. The names and shades are the classic CGA palette, Brown and all.
Transparent is not a color but the absence of one, which needs its own spelling because 0 is a legitimate black. Only TextBackground accepts it; as an ink it raises.
See also
Example
uses graph;
System.WriteLn (White);
System.WriteLn (Blue);
System.WriteLn (Transparent);
Shell
16777215
170
-1
Cos
function — unit math
Function
Returns the cosine of an angle given in radians.
Declaration
function Cos (X : Double) : Double;
Remarks
X is in radians, not degrees. Multiply a degree measure by Pi / 180.
The result is exact at the angles whose cosine is a whole number, but a quarter turn is not one of them: Cos (Pi / 2) answers 6.123233995736766E-17 rather than zero, because Pi / 2 is itself the nearest Double to a quarter turn and not the quarter turn. Compare against a tolerance rather than against zero.
A foreign declaration onto libm's cos.
See also
Example
uses math;
for var Deg := 0; Deg <= 180; Deg := Deg + 90 do
WriteLn (Str (Deg) + ' deg -> ' + Str (Cos (Deg * Pi / 180)));
Shell
0 deg -> 1.0
90 deg -> 6.123233995736766E-17
180 deg -> -1.0
Crt
a unit — unit crt
Function
graph's text mode, on a terminal instead of a window.
Declaration
uses crt;
InitCrt ();
Remarks
One world, as graph is, with the graphics half removed and a terminal underneath. The vocabulary is the same — Write, GotoXY, TextColor, the Window class stacked by Order, palettes, ReadKey — so a program written against one reads as a program written against the other. examples/ide-crt.a24 is examples/ide.a24 with three lines changed.
Every text verb in this reference marked unit graph and crt is in both and means the same in each. What crt does not have is everything that needs a pixel: no ViewPorts, no pen, no figures, no fonts.
⚠️ The constants are declared twice, not shared. uses is not transitive here, so a shared unit would force uses crt and uses of that shared unit merely to write LightCyan. One import for the thing you actually want is worth more than one definition.
⚠️ The screen is the terminal's own size, asked afresh rather than fixed, so TextCols and TextRows follow a resize between one frame and the next.
Colors reach the terminal as 24-bit where COLORTERM says it can, and as the nearest of the 256-color cube where it does not — so a palette lands exactly on a modern terminal and approximately on an old one.
⚠️ Nothing is emitted unless standard output is a terminal. Everything still composites, so a piped run produces its own output and nothing else, and this unit's own tests read a finished screen back without a byte escaping. See IsTerminal.
The screen is composited in memory and painted by difference: a frame that changes six cells sends six cells.
See also
InitCrt, IsTerminal, Window, Write
Example
See InitCrt.
DateTime
class — unit time
Function
A broken-down moment, as the host's calendar reads it.
Declaration
class DateTime;
var
Year : Integer;
Month : Integer;
Day : Integer;
Hour : Integer;
Minute : Integer;
Second : Integer;
DayOfWeek : Integer;
Epoch : Double;
function Text () : String;
Remarks
Answered by Now and At rather than constructed by a caller, and a snapshot rather than a live reading: a value held on to stays at the instant it came from.
Month runs 1 to 12 and Day 1 to 31, where C's struct tm counts months from zero — the seam is inside the unit and the field reads the way a date is written. DayOfWeek is 0 for Sunday. Second may read 60 in a leap second.
Epoch is the Double the moment came from, so the fraction of a second the other fields discard is still reachable, and two moments can be compared or subtracted without going through the calendar.
Text renders YYYY-MM-DD HH:MM:SS, zero-padded — ISO 8601's extended format with a space rather than a T. The zone is deliberately not shown: a DateTime does not know whether Now or UtcNow made it, and a string claiming a zone it cannot verify would be worse than one that says nothing.
This replaces Turbo Pascal's GetDate and GetTime, which wrote into four var parameters each. This language has none to write into — a scalar argument is unchanged on return — so a returned object is the answer, as ArcCoords already is.
See also
Example
uses time;
var M := UtcAt (0.0);
WriteLn (M.Text ());
WriteLn (M.Year, ' ', M.Month, ' ', M.Day, ' ', M.DayOfWeek);
// 1 January 1970 was a Thursday, and DayOfWeek counts Sunday as zero.
WriteLn (M.DayOfWeek = 4);
Shell
1970-01-01 00:00:00
1970 1 1 4
true
Delay
procedure — unit crt and graph
Function
Waits for a number of milliseconds.
Declaration
procedure Delay (Millis : Integer);
Remarks
Turbo Pascal's Delay, in both display units so that a program needs no extra uses to pace a frame.
⚠️ sound deliberately has none. A third copy made a bare Delay ambiguous in the two combinations worth writing — graph with sound is every game, crt with sound every console program that beeps — so the duplicate was dropped rather than taxing those with a qualifier. Play times itself, and a program timing raw tones by hand can say uses crt, whose Delay wants neither a terminal nor InitCrt.
⚠️ It needs nothing open. No window, no terminal, no sound device — a program that has called neither InitGraph nor InitCrt waits just the same.
It sleeps rather than spinning, so waiting costs no processor time.
⚠️ Nothing happens while it waits. No frame is presented and no key is collected, so a program that must stay responsive should wait in short steps and pump KeyPressed between them.
Zero or less returns at once rather than waiting forever.
⚠️ The language's clock () answers seconds, not milliseconds, so a 150-millisecond wait shows as 0.15. Reading it the other way makes every duration wrong by a thousand.
See also
Example
uses crt;
// It needs neither a window nor a terminal: this never calls InitCrt, and the
// wait is exactly the same.
var Start := clock ();
Delay (150);
// The language's clock answers SECONDS, not milliseconds.
var Waited := clock () - Start;
System.WriteLn ('asked for 150 ms');
System.WriteLn ('waited at least that: ', Waited >= 0.15);
System.WriteLn ('and not much more: ', Waited < 1.0);
// A senseless wait returns at once rather than never.
Delay (0);
Delay (0 - 5);
System.WriteLn ('zero and negative return at once');
Shell
asked for 150 ms
waited at least that: true
and not much more: true
zero and negative return at once
Delete
extension function — unit strings
Function
Returns its argument with a run of characters removed.
Declaration
extension function Delete (S : String, From : Integer, Count : Integer) : String;
Remarks
From is a 0-based index, as every string index in the language is.
Total over every index a caller might compute: a From at or past the end answers S unchanged, and a Count running past the end removes what there is. That totality is the reason the routine exists, because the obvious composition is not total — Copy (S, 0, From) + Copy (S, From + Count, Length (S)) raises whenever From + Count exceeds the length. Copy clamps an over-long count but refuses a start past the end, and the asymmetry is easy to miss until a generous count meets a short string.
A Count of zero answers S unchanged. A negative From or Count raises rather than counting back from the end; no routine in the library reads a negative index that way.
Insert is the inverse at the same index.
Both spellings work: Delete (S, 2, 2) and S.Delete (2, 2).
Raises Delete needs a start of zero or more. for a negative From, and Delete needs a count of zero or more. for a negative Count.
See also
Example
uses strings;
WriteLn ('abcdef'.Delete (2, 2));
WriteLn (Delete ('NONAME00.CPP', 6, 2));
// Total where the obvious composition is not: a count running past the end
// removes what there is, and a start past the end removes nothing.
WriteLn ('abcdef'.Delete (4, 99));
WriteLn ('abcdef'.Delete (99, 2));
Shell
abef
NONAME.CPP
abcd
abcdef
DelLine
procedures — unit graph and crt
Function
Deletes the cursor's row, or inserts a blank one.
Declaration
procedure DelLine (); // the screen
procedure DelLine (W : Window); // that window
procedure InsLine (); // the screen
procedure InsLine (W : Window); // that window
Remarks
The window forms are aliases of W.DelLine and W.InsLine. The bare forms are the base console layer — the root grid at Order 0 — and touch nothing else in the stack.
DelLine removes the row the cursor is on; every row below it moves up one, and the last row is left blank. InsLine opens a blank row at the cursor; every row below moves down one.
⚠️ They act within the surface's own walls, from the cursor's row to that surface's last — a window's rows, never the screen's. Graphics are untouched, on the same rule as ClrEol.
⚠️ The cursor does not move, in column or row. That is what makes DelLine twice delete two rows rather than the same one twice, and what lets InsLine and DelLine undo each other.
The blank row takes the current TextBackground — the one in force when the verb runs, not the one the rest of the surface was cleared to, so changing the background between a clear and a DelLine shows.
⚠️ What InsLine pushes off the bottom is gone. Nothing scrolls into being kept, here or in Turbo Pascal: a window holds its rows and no more. So the two are inverses only while nothing falls off the end.
Raises CloseGraph has closed this surface. on a window whose graph has gone, and Graph is not open. for the bare forms without a window.
See also
Clear, ClrEol, ClrScr, TextBackground, Window
Example
uses graph;
// A Window holds pixels, not characters, so telling a blank row from a
// written one means asking whether any of its pixels carry ink.
function Written (W : Window, Row : Integer) : Boolean;
begin
for var Y := (Row - 1) * CellHeight (); Y < Row * CellHeight (); Y := Y + 1 do
for var X := 0; X < W.PxW; X := X + 1 do
if W.Buf.GetInt ((Y * W.PxW + X) * 4) <> Blue - 16777216 then
Exit True;
Exit False;
end
InitGraph (640, 480, 'lines', False);
var W := Window (1, 1, 20, 4, 1);
TextBackground (W, Blue);
ClrScr (W);
Write (W, 'alpha');
GotoXY (W, 1, 2);
Write (W, 'beta');
GotoXY (W, 1, 3);
Write (W, 'gamma');
System.WriteLn ('written: ', Written (W, 1), ' ', Written (W, 2), ' ',
Written (W, 3), ' ', Written (W, 4));
// Delete the first row: the rest come up, and the last goes blank.
GotoXY (W, 1, 1);
DelLine (W);
System.WriteLn ('deleted: ', Written (W, 1), ' ', Written (W, 2), ' ',
Written (W, 3), ' ', Written (W, 4));
// Insert one back: the rest go down again. The cursor never moved, which is
// what lets the two undo each other.
InsLine (W);
System.WriteLn ('inserted:', Written (W, 1), ' ', Written (W, 2), ' ',
Written (W, 3), ' ', Written (W, 4));
System.WriteLn ('cursor at ', WhereX (W), ', ', WhereY (W));
CloseGraph ();
Shell
written: true true true false
deleted: true true false false
inserted:false true true false
cursor at 1, 1
Describe
extension function — unit reflect
Function
Returns a value written out with its fields, whatever the value is.
Declaration
extension function Describe (X : Any) : String;
Remarks
An instance renders as its class name and every field the class declares, parent-first and in declaration order — the order the core's Fields answers, which is the order a class seeds its fields. A field holding another instance or a collection is recursed into, so one call describes a whole graph.
This is the answer Str cannot give. An instance stringifies as Point instance, naming the class and saying nothing about the state, and a List of instances stringifies as a list of those words. That is a poor thing to be shown at the moment a test fails, which is why this exists.
A value that is not an instance answers something useful rather than failing. nil is nil, a collection is bracketed with its elements rendered the same way, and anything else is its Str. Text and a Char are quoted, which is what lets a reader tell the String '42' from the Integer 42, and makes an empty string visible rather than absent. A Buffer renders as its size alone, holding bytes rather than values.
A private field appears. private governs what a program may write and is settled before the program runs, so nothing records it at run time and a class whose state is private is still describable. A property does not appear, computing rather than storing.
Terminates on a cyclic graph. A container entered a second time renders as <Name seen> rather than being descended again, so a diamond shows its second reference as seen rather than repeating it. Without that guard the walk would recurse until the call stack was exhausted.
Both spellings work: Describe (X) and X.Describe ().
Never raises. Every value has a rendering, nil included.
See also
Example
uses reflect;
class Point;
var
X : Integer;
Y : Integer;
begin
constructor Init (AX : Integer, AY : Integer);
begin
X := AX;
Y := AY;
end
end
var P := Point (3, 4);
WriteLn (Str (P));
WriteLn (P.Describe ());
WriteLn (Describe ([Point (1, 2), Point (3, 4)]));
WriteLn (Describe (['name' : 'widget', 'tags' : [1, 2]]));
WriteLn (Describe (nil));
Shell
Point instance
Point (X: 3, Y: 4)
[Point (X: 1, Y: 2), Point (X: 3, Y: 4)]
['name': 'widget', 'tags': [1, 2]]
nil
DiskFree
functions — unit dos
Function
Return the free and total bytes on the filesystem holding a path.
Declaration
function DiskFree (Path : String) : Integer;
function DiskSize (Path : String) : Integer;
Remarks
DiskFree answers what an unprivileged program may actually write, excluding the blocks a filesystem reserves — a program asking "may I write this" is not asking about those. DiskSize counts every block, reserved ones included, which is what a size is. So DiskFree is never more than DiskSize and is usually less by more than what is stored.
⚠️ Neither takes a drive number. Turbo Pascal's DiskFree took one, which has no meaning here, and answered a LongInt, so it went wrong above 2 GB. A path is the portable question, and an Algol-24 Integer is unbounded — so these answer the true figure for a filesystem of any size.
Path may name any file or directory on the filesystem, not only its root; DiskFree ('.') asks about the one the program is running on.
Raises DiskFree: cannot read '<path>'. or DiskSize: cannot read '<path>'. where the filesystem could not be asked, which a path that is not there provokes.
See also
Example
uses dos;
// The figures are the host's, so only what is always true is printed.
WriteLn (DiskSize ('.') > 0);
WriteLn (DiskFree ('.') <= DiskSize ('.'));
// Any path on the filesystem answers for the whole of it.
WriteLn (DiskSize ('.') = DiskSize ('./dos.a24'));
Shell
true
true
true
Directory
class — unit file
Function
A directory being read, one entry at a time.
Declaration
constructor Directory (Path : String);
function AtEnd () : Boolean every entry answered
function Next () : String the next entry's name
procedure Close () released, and idempotent
Remarks
The core can make, remove and change directories [RT-026] and cannot list one, which is the gap this fills. Turbo Pascal's FindFirst and FindNext with their shared SearchRec, done as an object rather than a record the caller holds and passes back.
An iterator rather than a function answering everything, for the reason ReadAll learned: the incremental form is the primitive and the all-at-once form is sugar on it. Entries is that sugar, and is what most programs should use.
⚠️ . and .. are not answered. Every caller would filter them, and the ones that forgot would recurse forever.
⚠️ The order is the filesystem's, which is not sorted and not stable between runs. Sort the result if order matters.
Next answers a bare name with no directory part, so testing one means joining it back: IsDirectory (Path + '/' + Name).
Raises Directory: cannot open '<Path>'. when the path is absent, is not a directory, or cannot be read; Next: at end of directory. past the last entry, so a loop that forgets AtEnd fails rather than spinning; and <Member>: the directory is closed. once closed. Close may be called more than once, on the same terms as InFile's.
See also
Entries, IsDirectory, SplitPath, InFile
Example
uses file;
MkDir ('stock');
WriteAll ('stock/apples.txt', '12');
WriteAll ('stock/pears.txt', '7');
var D := Directory ('stock');
var Found := 0;
while not D.AtEnd () do
begin
var Name := D.Next ();
if not IsDirectory ('stock/' + Name) then Found := Found + 1;
end
D.Close ();
WriteLn ('files: ', Found);
Erase ('stock/apples.txt');
Erase ('stock/pears.txt');
RmDir ('stock');
Shell
files: 2
Entries
function — unit file
Function
Every entry in a directory, as a List of names.
Declaration
function Entries (Path : String) : List;
Remarks
The convenience form, standing to Directory as ReadLines stands to InFile. Names only, with no directory part, and without . or ...
⚠️ The order is the filesystem's and is not sorted.
Raises Entries: cannot open '<Path>'. on the same terms as Directory.
See also
Directory, ReadLines, IsDirectory
Example
uses file;
MkDir ('bin');
WriteAll ('bin/run', 'x');
WriteLn (Entries ('bin').Length, ' entry');
WriteLn (Entries ('bin')[0]);
Erase ('bin/run');
RmDir ('bin');
Shell
1 entry
run
DrawPoly
procedure, alias of ViewPort.DrawPoly — unit graph
Function
Draws the lines joining a list of points.
Declaration
procedure DrawPoly (V : ViewPort, Points : List);
Remarks
An alias of the method: DrawPoly (V, …) is V.DrawPoly (…).
Points is a List of two-number Lists:
DrawPoly (V, [[10, 10], [80, 10], [45, 70]]);
Turbo Pascal took a pointer and a count, because Pascal's array had no length of its own. The language has a List, so it is given one.
⚠️ The figure is not closed. Three points draw two lines; the way to close a triangle is to repeat its first point as a fourth. That is Turbo Pascal's rule and it is kept because it is the more general of the two — an open polyline is a thing worth drawing, and a closing segment nobody asked for cannot be taken back. FillPoly, when it arrives, will close of its own accord, a filled shape having no open reading.
Two points draw exactly a Line — there is a test asserting the two paint the same pixels.
⚠️ Every point is checked before any line is drawn, so a malformed list leaves the surface untouched rather than a figure broken off where the fault was.
Drawn with the pen's color and the current line style, segment by segment. The pen is not moved.
Raises DrawPoly wants at least two points., DrawPoly wants points of two numbers., and CloseGraph has closed this surface.
See also
FillPoly, Line, Rectangle, SetLineStyle
Example
uses graph;
InitGraph (640, 480, 'poly', False);
var V := ViewPort (60, 60, 400, 300, 1);
// A closed pentagon: the first point repeated as the last is what closes it.
SetColor (V, LightCyan);
DrawPoly (V, [[200, 30], [340, 130], [285, 270], [115, 270], [60, 130],
[200, 30]]);
// And an open path, which is what leaving the repeat off is for.
SetColor (V, Yellow);
SetLineStyle (V, DashedLn, 0, ThickWidth);
DrawPoly (V, [[80, 200], [140, 150], [200, 210], [260, 140], [320, 190]]);
Show (V);
System.WriteLn (GetX (V));
System.WriteLn (GetColor (V) = Yellow);
CloseGraph ();
Shell
1
true
Ellipse
procedure, alias of ViewPort.Ellipse — unit graph
Function
Draws an elliptical arc on a viewport.
Declaration
procedure Ellipse (V : ViewPort, X : Integer, Y : Integer, StartAngle : Integer,
EndAngle : Integer, XRadius : Integer, YRadius : Integer);
Remarks
An alias of the method: Ellipse (V, …) is V.Ellipse (…).
⚠️ Turbo Pascal's Ellipse takes angles, so it is an elliptical arc: a whole ellipse is the sweep 0, 360, and anything less is a piece of one. The angles mean what Arc's mean — degrees, zero at three o'clock, counterclockwise, which on a screen puts ninety degrees above the center.
With equal radii it is exactly Circle: there is a test asserting the two paint the same pixels, which is the strongest statement available that they compute one curve.
⚠️ The angle is the parametric one, not a bearing. On a wide ellipse the point at forty-five degrees is not forty-five degrees from the center as a protractor would have it — it is where the circle's forty-five lands once the circle is stretched. That is what Turbo Pascal drew, and it is what makes Ellipse (V, X, Y, 0, 90, A, B) the quadrant a reader expects; but it is worth knowing before computing an angle from a slope.
Drawn in the pen's color, patterned by the line style, and thickened by drawing the neighboring ellipses — which keeps a thick ellipse an ellipse rather than a ring of uneven width. The pen is not moved.
The outline only; a filled one waits on FillEllipse.
Raises Ellipse needs radii of zero or more. and CloseGraph has closed this surface.
See also
Arc, Circle, GetArcCoords, SetLineStyle
Example
uses graph;
InitGraph (640, 480, 'ellipse', False);
var V := ViewPort (60, 60, 400, 300, 1);
// A whole ellipse, and a quarter of a wider one drawn thick over it.
SetColor (V, LightCyan);
Ellipse (V, 200, 150, 0, 360, 160, 90);
SetColor (V, Yellow);
SetLineStyle (V, SolidLn, 0, ThickWidth);
Ellipse (V, 200, 150, 0, 90, 120, 60);
Show (V);
// Each radius governs its own axis: 160 across, 90 down.
System.WriteLn (V.Buf.GetInt ((149 * 400 + 359) * 4) <> 0);
System.WriteLn (V.Buf.GetInt ((59 * 400 + 199) * 4) <> 0);
CloseGraph ();
Shell
true
true
EnableMouse
procedures and functions — unit graph and crt
Function
Starts and stops reporting the mouse, and says where it is.
Declaration
procedure EnableMouse ();
procedure DisableMouse ();
function MouseEnabled () : Boolean;
function MouseX () : Integer;
function MouseY () : Integer;
function MouseButtons () : Integer;
Remarks
⚠️ The mouse is off until a program asks for it. Turbo Vision always had it on, but it owned the whole screen; a library's default should cost nothing. Off means a program reading only keys is unaffected, nothing accumulates in a queue nobody drains, and — in crt — the terminal is never sent the tracking escapes that a terminal ignoring them would print as junk.
MouseX and MouseY are polled rather than queued, which is the older way and still the right one when all a program wants is where the pointer is now. They answer 1, 1 until the mouse has been enabled and moved.
Coordinates are the screen's own space: logical pixels in graph, cells in crt. graph maps SDL's window pixels back into the logical space, which is the inverse of the scaling that puts a surface on screen — without it every coordinate would be wrong at any window size but one to one.
MouseButtons answers the button bits summed.
⚠️ Closing the screen forgets the mouse. A new window or screen starts with it off, wherever the last one left it, and with no stale pointer position.
Raises Graph is not open. or Crt is not open.
See also
Example
uses graph;
InitGraph (1280, 800, 'mouse', False);
// Off until asked for, so a program that reads only keys is unaffected and
// nothing piles up in a queue nobody drains.
System.WriteLn ('before: ', MouseEnabled ());
EnableMouse ();
System.WriteLn ('after: ', MouseEnabled ());
// Two surfaces, one over the other.
var Under := ViewPort (100, 100, 300, 200, 1);
var Over := ViewPort (200, 150, 300, 200, 2);
// The stack decides what a point is over. The root grid covers the whole
// screen, so a point over nothing else answers it rather than nil.
System.WriteLn ('at 120,120: over Under ', SurfaceAt (120, 120) = Under);
System.WriteLn ('at 250,200: over Over ', SurfaceAt (250, 200) = Over);
System.WriteLn ('at 5,5: the screen ', SurfaceAt (5, 5) = Root);
System.WriteLn ('at 0,5: nothing ', SurfaceAt (0, 5) = nil);
// Reordering is an assignment; nothing else has to be told.
Under.Order := 3;
System.WriteLn ('reordered: over Under ', SurfaceAt (250, 200) = Under);
CloseGraph ();
Shell
before: false
after: true
at 120,120: over Under true
at 250,200: over Over true
at 5,5: the screen true
at 0,5: nothing true
reordered: over Under true
Event
class — unit graph and crt
Function
Something that happened: a key, or the mouse.
Declaration
constructor Event (Kind : Integer, Key : Char, X : Integer, Y : Integer,
Buttons : Integer, Surface : Any, LocalX : Integer,
LocalY : Integer);
Kind : Integer one of the EventKinds
Key : Char the key, when Kind is EventKey
X, Y : Integer where, in the screen's own space
Buttons : Integer which buttons are down, as bits
Surface : Any the topmost surface under the pointer, or nil
LocalX, LocalY : Integer the same point in that surface's own coordinates
Remarks
Turbo Vision's TEvent, with the two fields it had to compute by hand filled in already.
⚠️ Surface and LocalX/LocalY are the point of this. Working out which view a click landed on, and where within it, was TView's job and a substantial part of that framework. A stack ordered by Order answers both, so the event carries them and no caller repeats the work:
if E.Surface = Board then Play (KeyAtPoint (E.LocalX, E.LocalY));
LocalX/LocalY are in that surface's own space — cells for a Window, pixels for a ViewPort — which is what a caller wants to compare against.
X and Y are the screen's own space: logical pixels in graph, cells in crt. See SurfaceAt.
⚠️ Key means something only when Kind is EventKey. It is a space otherwise, the language having no null Char.
For a key event the mouse fields carry the pointer's last known position, which is occasionally useful and never wrong.
See also
EventKinds, ReadEvent, SurfaceAt, Window
Example
See ReadEvent.
EventKinds
constants — unit graph and crt
Function
What an Event is, and which mouse buttons are down.
Declaration
const EventNone := 0; const MouseLeft := 1;
const EventKey := 1; const MouseMiddle := 2;
const EventMouseDown := 2; const MouseRight := 4;
const EventMouseUp := 3;
const EventMouseMove := 4;
Remarks
Both units declare the same values, so a program written against one reads against the other.
The buttons are bits, so a chord is their sum and a test is a division:
if E.Buttons div MouseLeft mod 2 = 1 then ...
Turbo Pascal's Crt and Graph had no mouse at all — it was INT 33h, called by hand. Turbo Vision was where it landed, and its TEvent carried keys and mouse in one queue because anything with both has to interleave them.
There is no wheel event. A terminal reports the wheel as a button in the sixties and crt drops it rather than inventing a click that never happened; graph does not queue SDL's wheel event either. It can be added when something wants it.
See also
Example
See ReadEvent.
Environment
functions — unit dos
Function
Return every environment entry as a List, and split one into its name and value.
Declaration
function Environment () : List;
function EnvName (Entry : String) : String;
function EnvValue (Entry : String) : String;
Remarks
One List rather than Turbo Pascal's EnvCount and EnvStr pair, which were two members expressing one sequence because DOS Pascal had no list type. This language has one.
The entries keep the host's own NAME=VALUE form. EnvName and EnvValue split on the first = only, a value being allowed to contain more — EnvValue ('ARGS=-c a=b') is -c a=b. An entry with no = at all answers the whole of it as the name and the empty string as the value.
The order is the host's and means nothing. A name may in principle appear twice, in which case GetEnv answers whichever the host prefers. Reading one variable by name goes through GetEnv and not through here.
None of the three raises; an environment of no entries answers an empty List.
See also
Example
uses dos;
// The NAME=VALUE form, split on the first equals only.
WriteLn (EnvName ('TERM=xterm-256color'));
WriteLn (EnvValue ('TERM=xterm-256color'));
WriteLn (EnvValue ('ARGS=-c a=b'));
// Every host sets PATH, whatever it holds.
var Found := False;
for var Entry in Environment () do
if EnvName (Str (Entry)) = 'PATH' then Found := True;
WriteLn (Found);
Shell
TERM
xterm-256color
-c a=b
true
Exec
function — unit dos
Function
Runs a program with the given arguments and returns its exit status.
Declaration
function Exec (Path : String, Args : List) : Integer;
Remarks
⚠️ No shell, and the argument list is why. The arguments reach the program as a vector, so one containing a space, a quote, a semicolon or a newline arrives as a single argument and cannot become syntax. Turbo Pascal's Exec took a command line, which is where that hazard lives, and C's system would reintroduce it.
Because there is no shell there is also no PATH search, no globbing and no redirection. Path must name the program — '/bin/echo', not 'echo'. That is the cost of the safety, and the right side of the trade for a library.
Args holds the arguments after the program's own name; the program sees Path as its argv[0], as it expects. The environment is inherited, and the call waits for the program to finish.
The status is the program's own exit code, or 128 plus the signal number where it was killed — the shell's convention, and unambiguous because an exit code cannot exceed 255. A program that could not be started raises instead, since a command that never ran is not a command that failed.
Raises Exec: cannot run '<path>'. where the program could not be started, and Exec: too many arguments. beyond the 1023 the vector holds.
See also
Example
<!-- check-reference: posix-only -->
uses dos;
// No shell: the arguments reach the program as a vector.
var Args := List ();
Args.Add ('one');
Args.Add ('two words');
Args.Add ('semi;colon');
WriteLn (Exec ('/bin/echo', Args));
// The exit status is the program's own.
WriteLn (Exec ('/usr/bin/true', List ()));
WriteLn (Exec ('/usr/bin/false', List ()));
Shell
one two words semi;colon
0
0
1
Exp
function — unit math
Function
Returns e raised to the power of its argument.
Declaration
function Exp (X : Double) : Double;
Remarks
Exp (1.0) is e itself, 2.718281828459045.
Ln undoes Exp exactly — Ln (Exp (X)) answers X — but the reverse round trip does not always hold: Exp (Ln (3.0)) is 3.0000000000000004. That is ordinary floating-point rounding rather than anything either routine does.
A foreign declaration onto libm's exp.
See also
Example
uses math;
WriteLn (Exp (0.0));
WriteLn (Exp (1.0));
Shell
1.0
2.718281828459045
FillEllipse
procedure, alias of ViewPort.FillEllipse — unit graph
Function
Fills and outlines a whole ellipse on a viewport.
Declaration
procedure FillEllipse (V : ViewPort, X : Integer, Y : Integer,
XRadius : Integer, YRadius : Integer);
Remarks
An alias of the method: FillEllipse (V, …) is V.FillEllipse (…).
Sector swept the whole way round, exactly as Circle is Arc — filled with the current fill pattern and color, then outlined with the pen and the current line style. No radii are drawn: a whole turn's two coincide.
It takes no angles, because Turbo Pascal's did not. A wedge is Sector's business.
⚠️ A filled circle is this with equal radii. Turbo Pascal has no FillCircle, and neither does this — FillEllipse (V, X, Y, R, R) is it, and so is PieSlice (V, X, Y, 0, 360, R). There are tests asserting all three agree pixel for pixel, which is the same statement Circle and Ellipse make about their outlines.
With EmptyFill it is outlined and hollow. The fill and the outline are separate pens, and the pen is not moved.
Raises FillEllipse needs radii of zero or more. and CloseGraph has closed this surface.
See also
Ellipse, GetArcCoords, PieSlice, Sector, SetFillStyle
Example
uses graph;
InitGraph (640, 480, 'fillellipse', False);
var V := ViewPort (60, 60, 420, 320, 1);
// Three ellipses, each filled in its own pattern and edged in white.
SetColor (V, White);
SetFillStyle (V, SolidFill, LightRed);
FillEllipse (V, 110, 160, 90, 60);
SetFillStyle (V, HatchFill, LightCyan);
FillEllipse (V, 240, 160, 60, 110);
// Equal radii: the filled circle Turbo Pascal never named.
SetFillStyle (V, InterleaveFill, Yellow);
FillEllipse (V, 350, 160, 55, 55);
Show (V);
// Wide reaches further across than down; the circle is as wide as it is tall.
System.WriteLn (V.Buf.GetInt ((159 * 420 + 189) * 4) <> 0);
System.WriteLn (V.Buf.GetInt ((59 * 420 + 109) * 4) = 0);
CloseGraph ();
Shell
true
true
FillPoly
procedure, alias of ViewPort.FillPoly — unit graph
Function
Fills and outlines the polygon through a list of points.
Declaration
procedure FillPoly (V : ViewPort, Points : List);
Remarks
An alias of the method: FillPoly (V, …) is V.FillPoly (…).
Points is a List of two-number Lists, as DrawPoly takes.
⚠️ Unlike DrawPoly, the figure closes itself. The last point joins the first whether or not it was repeated, because a filled shape has no open reading. Repeating it anyway is harmless — the closing edge is then of no length and crosses nothing — and a test asserts the two spellings paint identically.
Filled with the current fill pattern and color, then outlined with the pen and the current line style, so a polygon may be laid in one color and edged in another. With EmptyFill it is outlined and hollow.
⚠️ The fill is by the even-odd rule, which is what a scanline fill means and what Turbo Pascal did: a row is crossed by the edges, the crossings are sorted, and the spans between the first and second, third and fourth, and so on are painted. A self-crossing polygon therefore fills in bands — the classic five-pointed star comes out with a hollow pentagon at its heart, which is correct rather than a defect.
A rectangle given as four points is exactly Bar with a Rectangle over it, pixel for pixel — which also pins the half-open edge rule that keeps a shape from leaking at its corners.
The geometry is in Algol-24 — which row is crossed where is the logic — and only the spans are handed to C, one call per span. That is a different split from Bar's and PieSlice's, where the shape itself went over; a polygon's shape is its points, and those are the caller's.
The pen is not moved.
Raises FillPoly wants at least three points., FillPoly wants points of two numbers., and CloseGraph has closed this surface.
See also
Example
uses graph;
InitGraph (640, 480, 'fillpoly', False);
var V := ViewPort (60, 40, 400, 400, 1);
// A filled arrow: closed of its own accord, so the first point is not
// repeated at the end.
SetColor (V, White);
SetFillStyle (V, SolidFill, LightCyan);
FillPoly (V, [[40, 140], [180, 140], [180, 90], [280, 175],
[180, 260], [180, 210], [40, 210]]);
// And a star, which the even-odd rule leaves hollow at its heart.
SetFillStyle (V, HatchFill, Yellow);
FillPoly (V, [[200, 280], [224, 390], [112, 320], [288, 320], [176, 390]]);
Show (V);
// The arrow's shaft is filled; the star's middle is not.
System.WriteLn (V.Buf.GetInt ((174 * 400 + 99) * 4) <> 0);
System.WriteLn (V.Buf.GetInt ((339 * 400 + 199) * 4) = 0);
CloseGraph ();
Shell
true
true
FillSettings
classes — unit graph
Function
The fill and line state a viewport is holding, answered whole.
Declaration
constructor FillSettings (Style : Integer, Color : Integer);
Style : Integer one of the FillStyles
Color : Integer the ink figures are filled in
constructor LineSettings (Style : Integer, Pattern : Integer,
Thickness : Integer);
Style : Integer one of the LineStyles
Pattern : Integer the sixteen bits walked along a line
Thickness : Integer the width in pixels
Remarks
Turbo Pascal's FillSettingsType and LineSettingsType, answered by GetFillSettings and GetLineSettings rather than written into a var record — the same reasoning as ArcCoords.
⚠️ The field names are this library's, not Turbo Pascal's. FillSettings.Style is Turbo Pascal's Pattern field, renamed so it matches SetFillStyle(Style, Color); calling it Pattern here would invite a reader to expect the eight rows that GetFillPattern answers. LineSettings.Style is Turbo Pascal's LineStyle, on the same reasoning. Every field is named for the argument that sets it, so a saved state goes back through the setter without translation:
SetLineStyle (V, Line.Style, Line.Pattern, Line.Thickness);
They are snapshots. A later SetFillStyle makes a new one rather than changing an existing one, so a value held on to still describes the state it came from.
See also
ArcCoords, GetFillSettings, SetFillStyle, SetLineStyle, ViewPort
Example
See GetFillSettings.
FillStyles
constants — unit graph
Function
The fill patterns SetFillStyle takes.
Declaration
const EmptyFill := 0; const HatchFill := 7;
const SolidFill := 1; const XHatchFill := 8;
const LineFill := 2; const InterleaveFill := 9;
const LtSlashFill := 3; const WideDotFill := 10;
const SlashFill := 4; const CloseDotFill := 11;
const BkSlashFill := 5; const UserFill := 12;
const LtBkSlashFill := 6;
Remarks
Turbo Pascal's thirteen names, kept whole because a program written to them should still read. Each is an eight-by-eight bit pattern tiled across the figure being filled, one bit to the pixel.
The bits themselves are this library's own — Turbo Pascal's exact patterns were a BGI implementation detail rather than a promise, the same reasoning that governs the line styles.
⚠️ EmptyFill paints nothing at all, leaving whatever is beneath showing through. Turbo Pascal filled with the background color there, which a surface that is transparent by default has no equivalent for — leaving the pixels alone is what empty means on a stack of surfaces.
⚠️ UserFill is not chosen by name. It is what SetFillPattern sets, since a pattern without bits would be meaningless; passing it to SetFillStyle raises.
See also
Example
See SetFillStyle.
FloodFill
procedure, alias of ViewPort.FloodFill — unit graph
Function
Fills the region around a point, stopping at pixels of the border color.
Declaration
procedure FloodFill (V : ViewPort, X : Integer, Y : Integer, Border : Integer);
Remarks
An alias of the method: FloodFill (V, …) is V.FloodFill (…).
The only figure that reads the surface. Every other one knows the pixels it covers from its parameters — Bar from its corners, Sector from its radii and angles — while a flood has to look at what is already drawn and follow it.
⚠️ A boundary fill, as Turbo Pascal's was. The region is every pixel reachable from the seed without crossing one of the border color — not every pixel matching the seed's own. That is the fill an outlined figure wants, and an outlined figure is what a flood is usually aimed at: Circle and then FloodFill inside it is the filled disc drawn the long way round.
Follow that definition and two consequences fall out, both of them the point rather than surprises. A gap in the outline leaks — the paint escapes through it and floods whatever lies beyond, because the paint goes exactly where the drawn border does not stop it. And an outline divides the surface in two: flood inside it, flood outside it, and between them and the border every pixel is accounted for.
Border may be Transparent, which is the useful one on a fresh surface — the untouched pixels are then the border, so the flood spreads exactly as far as the paint already there and recolors a blob without touching what surrounds it.
The current fill pattern and color are used, tiled from the surface's origin as every fill is, so a patterned flood leaves most of the region unpainted while still crossing all of it. EmptyFill paints nothing. The pen is not moved, a flood being a figure rather than a journey.
A seed off the viewport, or one already standing on the border color, fills nothing and does not raise — the edge is the clip, as it is for PutPixel.
Raises FloodFill wants a color or Transparent. and CloseGraph has closed this surface.
See also
Bar, Circle, GetPixel, SetFillStyle
Example
uses graph;
InitGraph (640, 480, 'flood', False);
var V := ViewPort (100, 60, 200, 200, 1);
// An outline, and then the paint poured inside it.
SetColor (V, LightCyan);
Circle (V, 100, 100, 80);
SetFillStyle (V, SolidFill, Blue);
FloodFill (V, 100, 100, LightCyan);
Show (V);
System.WriteLn (GetPixel (V, 100, 100) = Blue); // the middle is filled
System.WriteLn (GetPixel (V, 100, 25) = Blue); // and so is the top
System.WriteLn (GetPixel (V, 5, 5) = Transparent); // outside is untouched
CloseGraph ();
Shell
true
true
true
Frac
function — unit math
Function
Returns the fractional part of its argument.
Declaration
function Frac (X : Double) : Double;
Remarks
The result carries the sign of X. Frac (-3.5) is -0.5, not 0.5 and not 0.3 — the definition is X - Int (X), and Int truncates toward zero.
The identity that holds is Int (X) + Frac (X) = X. That the result is non-negative is not one, and a program wanting a non-negative fraction has to say so itself.
Accuracy is the subtraction's. Frac (3.7) is 0.7000000000000002, because 3.7 has no exact Double to begin with — that is arithmetic rather than anything this routine does.
Above 2^52 a Double has no fractional bits left, so Frac is 0.0 from there upward.
Written in Algol-24, over Int.
See also
Example
uses math;
WriteLn (Frac (3.5));
WriteLn (Frac (-3.5));
WriteLn (Int (3.5) + Frac (3.5));
WriteLn (Frac (3.7));
Shell
0.5
-0.5
3.5
0.7000000000000002
GetArcCoords
function, alias of ViewPort.GetArcCoords — unit graph
Function
Where the last arc on a viewport was centered, began and ended.
Declaration
function GetArcCoords (V : ViewPort) : ArcCoords;
Remarks
An alias of the method: GetArcCoords (V) is V.GetArcCoords (). It answers an ArcCoords.
What it is for is joining something to a curve: a line continuing from the end of an Arc, a label at the lip of a PieSlice, a second figure hung off the first.
⚠️ Recomputing those points from the angles is the obvious alternative and is subtly wrong. Rounding puts the recomputed point a pixel away from the drawn one often enough to show as a gap, and the drawing loop's rounding is not something a caller should have to reproduce. The endpoints here are computed the way the drawing loop computes its pixels, so what is answered is a point the figure really reached.
All six curve verbs record, which is more than Turbo Pascal promised:
| verb | records because |
|---|---|
Arc | it walks the curve |
Ellipse | it walks the curve |
Circle | drawn through Arc |
PieSlice | outlined with Arc |
Sector | outlined with Ellipse |
FillEllipse | drawn through Sector, so through Ellipse |
Turbo Pascal documented only the first three of those. Recording in the two primitives rather than in the six verbs is what makes the other three free — and is why they cannot drift apart from each other.
For a whole turn the two endpoints coincide, a closed figure having no two ends. Figures that draw no curve — Line, Rectangle, Bar, DrawPoly — leave the answer alone.
Each surface keeps its own, as it keeps its own pen.
Raises No arc has been drawn on this surface. before any of the six have run — six meaningless numbers would be worse than a refusal, since nothing about them would look wrong at the call site — and CloseGraph has closed this surface. once the window has gone.
See also
Arc, ArcCoords, PieSlice, Sector
Example
uses graph;
InitGraph (640, 480, 'arccoords', False);
var V := ViewPort (100, 60, 300, 300, 1);
SetColor (V, LightCyan);
Arc (V, 150, 150, 0, 120, 100);
var C := GetArcCoords (V);
System.WriteLn ('center ', C.X, ' ', C.Y);
System.WriteLn ('start ', C.XStart, ' ', C.YStart);
System.WriteLn ('end ', C.XEnd, ' ', C.YEnd);
// The end is a pixel the arc really drew, which is why a line started there
// meets the curve instead of landing beside it.
System.WriteLn ('on the arc: ', GetPixel (V, C.XEnd, C.YEnd) = LightCyan);
SetColor (V, Yellow);
PenTo (V, C.XEnd, C.YEnd);
LineRel (V, -50, -30);
Show (V);
CloseGraph ();
Shell
center 150 150
start 250 150
end 100 63
on the arc: true
GetAspectRatio
function — unit graph
Function
How much wider than tall a logical pixel appears on the screen.
Declaration
function GetAspectRatio () : Double;
Remarks
The space Windows and ViewPorts are measured in is fixed by the grid and the font — TextCols () * CellWidth () by TextRows () * CellHeight (), which is 1280 by 800 for the default 80 by 25 — and it is scaled independently in X and Y to fill whatever window actually opened.
⚠️ When those two scales differ, a logical pixel is not square, and a Circle drawn with equal radii shows as an oval. This is Turbo Pascal's problem arriving by a different road: there it was the display hardware, here it is the stretch.
1.0 is square. Above 1.0 a logical pixel shows wider than tall; below, taller than wide. A circle that should look round is:
Ellipse (V, X, Y, 0, 360, Round (R / GetAspectRatio ()), R);
The ratio follows the window's shape, not its size — every 4:3 window answers 0.8333…, because the logical space is 16:10 whatever the window. TextMode changes it too, by changing the logical space: 40 columns in the same window doubles it.
⚠️ Circle does not correct itself, where Turbo Pascal's did. The logical space is the program's own coordinate system, and a radius meaning the same in both directions there is what keeps Circle (X, Y, R), PieSlice (X, Y, 0, 360, R) and FillEllipse (X, Y, R, R) one shape. Correcting for the screen is the caller's to ask for, and this is the asking.
Turbo Pascal answered two Words with the vertical one pegged at 10000 — fixed point standing in for a fraction the machine could not afford. The language has Doubles, so this answers the fraction itself.
The background is not affected: its pixels are the window's own, one to one, so they are square whatever this answers.
Raises Graph is not open. without a window.
See also
CellWidth, Circle, Ellipse, GetMaxX, TextMode
Example
uses graph;
uses math;
InitGraph (640, 480, 'aspect', False);
// The logical space is fixed by the grid and the font. The window it is
// stretched into need not be the same shape, and here it is not.
System.WriteLn ('logical ', TextCols () * CellWidth (), ' by ',
TextRows () * CellHeight ());
System.WriteLn ('window ', GetMaxX (), ' by ', GetMaxY ());
System.WriteLn ('aspect ', GetAspectRatio ());
var V := ViewPort (100, 100, 400, 400, 1);
var R := 100;
// Equal radii are equal in the logical space, so this shows as an oval.
SetColor (V, DarkGray);
Circle (V, 200, 200, R);
// Cancelling the stretch makes it look round on the screen.
var XR := Round (R / GetAspectRatio ());
SetColor (V, Yellow);
Ellipse (V, 200, 200, 0, 360, XR, R);
Show (V);
System.WriteLn ('corrected x radius ', XR);
CloseGraph ();
Shell
logical 1280 by 800
window 640 by 480
aspect 0.8333333333333334
corrected x radius 120
GetColor
function, alias of ViewPort.GetColor — unit graph
Function
Returns the color a viewport's pen is drawing in.
Declaration
function GetColor (V : ViewPort) : Integer;
Remarks
An alias of the method: GetColor (V) is V.GetColor ().
The pen's color governs everything the viewport draws — the Line family and the OutText pair alike. A fresh viewport draws in White.
Raises CloseGraph has closed this surface. once the window it belongs to has gone.
See also
Example
See SetColor, which sets it and reads it back.
GetEnv
functions — unit dos
Function
Return an environment variable's value, and whether it is set at all.
Declaration
function GetEnv (Name : String) : String;
function HasEnv (Name : String) : Boolean;
Remarks
GetEnv answers '' for a variable that is not set rather than raising, which is what makes GetEnv ('EDITOR') usable without asking first.
HasEnv exists because that conflates two things: a variable set to the empty string and a variable not set at all both read as '', and they mean different things — ALG_SOUND= is a request this library would honour, and no ALG_SOUND at all is not.
The value is copied out of the host's environment rather than pointed at. No foreign function in this library answers a pointer, because a String returned from C borrows the bytes and a later call could corrupt it — see DEFECTS.md H-2 — so this asks the length, sizes a buffer to it, and reads it back.
Neither raises.
See also
Example
uses dos;
// A name no host sets, so the answer is the same everywhere -- and the two
// questions differ: an unset variable reads as empty, and HasEnv says why.
WriteLn ('[' + GetEnv ('ALG_NO_SUCH_VARIABLE') + ']');
WriteLn (HasEnv ('ALG_NO_SUCH_VARIABLE'));
// PATH is set on every host, whatever it holds.
WriteLn (HasEnv ('PATH'));
Shell
[]
false
true
GetFillPattern
function, alias of ViewPort.GetFillPattern — unit graph
Function
The eight rows of the fill pattern in force.
Declaration
function GetFillPattern (V : ViewPort) : List;
Remarks
An alias of the method: GetFillPattern (V) is V.GetFillPattern ().
Eight Integers, each the eight bits of one row with the high bit leftmost — the same shape SetFillPattern takes, so what comes out of one viewport goes straight into another:
SetFillPattern (W, GetFillPattern (V), LightCyan);
⚠️ It answers the bits actually in force, whichever style set them. Turbo Pascal's GetFillPattern answered the last pattern given to SetFillPattern and nothing else, so asking it after a built-in style told you about a pattern that was no longer painting anything. Here InterleaveFill answers its own checker.
⚠️ The list is a copy. Changing it changes nothing on the viewport, so what is answered cannot be used to alter what a surface paints without asking.
Raises CloseGraph has closed this surface. once the window has gone.
See also
FillStyles, GetFillSettings, SetFillStyle
Example
uses graph;
InitGraph (640, 480, 'pattern', False);
var V := ViewPort (50, 50, 100, 100, 1);
// A built-in style answers the bits it stands for, not merely its number.
SetFillStyle (V, InterleaveFill, Yellow);
for var Row in GetFillPattern (V) do
System.Write (Row, ' ');
System.WriteLn ('');
// The same eight rows go straight back in, here into another surface.
var W := ViewPort (200, 50, 100, 100, 1);
SetFillPattern (W, GetFillPattern (V), LightCyan);
System.WriteLn ('W is UserFill: ', GetFillStyle (W) = UserFill);
System.WriteLn ('bits carried: ', GetFillPattern (W)[0] = 170);
CloseGraph ();
Shell
170 85 170 85 170 85 170 85
W is UserFill: true
bits carried: true
GetFillSettings
functions, aliases of ViewPort.GetFillSettings and GetLineSettings — unit graph
Function
Reads back the fill or line state a viewport is holding.
Declaration
function GetFillSettings (V : ViewPort) : FillSettings;
function GetLineSettings (V : ViewPort) : LineSettings;
Remarks
Aliases of the methods, answering a FillSettings or a LineSettings.
What they are for is saving a state and putting it back — before a routine that will change the pen, so it can be handed over unchanged afterward. Every field is named for the argument that sets it, so a restore is one call and no translation:
var Line := GetLineSettings (V);
// ... something that changes the pen ...
SetLineStyle (V, Line.Style, Line.Pattern, Line.Thickness);
GetFillStyle and GetFillColor answer the two halves of the fill separately and are shorter when only one is wanted. GetLineSettings has no such pair: it is the only way to read the line state back, there being no GetLineStyle.
⚠️ Pattern is the bits actually walked, not the argument given. A built-in style answers what it stands for — SolidLn answers 65535, DashedLn answers 61680 — where a caller usually passes 0 beside it. Turbo Pascal answered the argument, which said nothing at all for four of its five styles. Feeding what is answered back into SetLineStyle restores the same line either way, since the style is restored alongside it.
Both are snapshots, not views onto the surface.
Raises CloseGraph has closed this surface. once the window has gone.
See also
FillSettings, GetFillPattern, SetFillStyle, SetLineStyle
Example
uses graph;
InitGraph (640, 480, 'settings', False);
var V := ViewPort (50, 50, 200, 100, 1);
SetFillStyle (V, XHatchFill, LightGreen);
SetLineStyle (V, DashedLn, 0, 5);
// Save both states before something that will change them.
var Fill := GetFillSettings (V);
var Line := GetLineSettings (V);
System.WriteLn ('fill style ', Fill.Style, ' color ', Fill.Color);
System.WriteLn ('line style ', Line.Style, ' pattern ', Line.Pattern,
' thickness ', Line.Thickness);
SetFillStyle (V, SolidFill, Red);
SetLineStyle (V, DottedLn, 0, 1);
// And put them back, the fields being the setters' own arguments.
SetFillStyle (V, Fill.Style, Fill.Color);
SetLineStyle (V, Line.Style, Line.Pattern, Line.Thickness);
System.WriteLn ('restored ', GetFillStyle (V) = XHatchFill, ' ',
GetLineSettings (V).Thickness = 5);
CloseGraph ();
Shell
fill style 8 color 5635925
line style 3 pattern 61680 thickness 5
restored true true
GetImage
function and procedure, aliases of ViewPort.GetImage and PutImage — unit graph
Function
Lifts a rectangle of pixels off a viewport, and draws one back.
Declaration
function GetImage (V : ViewPort, X1 : Integer, Y1 : Integer,
X2 : Integer, Y2 : Integer) : Image;
procedure PutImage (V : ViewPort, X : Integer, Y : Integer,
Img : Image, Mode : Integer);
Remarks
Aliases of the methods. GetImage answers an Image; PutImage draws one with its top-left corner at X, Y.
⚠️ Neither step Turbo Pascal required is needed. There the caller sized a block with ImageSize, allocated it with GetMem, and only then called GetImage. An Image carries its own storage, so this is one call. ImageSize remains and says what a region will cost.
The corners are inclusive, so GetImage (V, 1, 1, 8, 8) is sixty-four pixels. A rectangle reaching past the edge reads Transparent there rather than raising, and PutImage drops pixels that fall outside — the edge is the clip, as it is for GetPixel.
Mode is one of the put modes and says how the image combines with what is already on the surface. Two of them do the work:
CopyPut | replaces the rectangle, the image's transparency included |
TransparentPut | lays only what the image painted, leaving the rest showing |
⚠️ CopyPut restores exactly what was taken, which is what makes save-scribble-restore work. TransparentPut is the sprite one, and is the mode Turbo Pascal had no equivalent of.
XorPut written twice puts the surface back — (a xor b) xor b is a whatever the bits mean — which is the classic way to move a figure over a background without saving the background at all.
The pen is not moved, an image being a figure rather than a journey.
Raises GetImage wants X2 >= X1 and Y2 >= Y1., PutImage wants a known mode., and CloseGraph has closed this surface. once the window has gone.
See also
GetPixel, Image, ImageSize, PutModes
Example
uses graph;
InitGraph (640, 480, 'images', False);
var V := ViewPort (50, 50, 300, 200, 1);
// A figure drawn on the bare surface, so what surrounds it is unpainted.
SetFillStyle (V, SolidFill, Red);
SetColor (V, Yellow);
PieSlice (V, 40, 40, 30, 300, 24);
var Sprite := GetImage (V, 16, 16, 65, 65);
System.WriteLn ('sprite ', Sprite.W, ' by ', Sprite.H,
', costing ', ImageSize (16, 16, 65, 65), ' bytes');
// A patterned band to lay it over.
SetFillStyle (V, HatchFill, DarkGray);
Bar (V, 1, 100, 300, 170);
PutImage (V, 20, 110, Sprite, CopyPut);
PutImage (V, 120, 110, Sprite, TransparentPut);
Show (V);
// CopyPut brought the sprite's own unpainted surround with it, so the band
// is gone inside that rectangle. TransparentPut laid only what was painted.
System.WriteLn ('band under the copy: ',
GetPixel (V, 21, 111) <> Transparent);
System.WriteLn ('band under the transparent: ',
GetPixel (V, 121, 111) <> Transparent);
System.WriteLn ('but both drew the figure: ',
GetPixel (V, 44, 134) = GetPixel (V, 144, 134));
CloseGraph ();
Shell
sprite 50 by 50, costing 10000 bytes
band under the copy: false
band under the transparent: true
but both drew the figure: true
GetMaxX
function — unit graph
Function
Returns the highest X a program can draw to — the window's width.
Declaration
function GetMaxX () : Integer;
Remarks
The screen counts from 1, pixels and cells alike, so the count is the last index: for var X := 1; X <= GetMaxX (); visits every column with no minus one anywhere — the off-by-one Turbo Pascal's 0-based GetMaxX was famous for does not exist here.
⚠️ The answer describes the window that actually opened, not the request. Under a fullscreen InitGraph it is the desktop's width, whatever size was asked for.
Raises Graph is not open. before InitGraph or after CloseGraph, when there is no window to measure.
For how big a window could be, before opening one, see ScreenWidth — that is a different question, and it has its own name so that this one can keep meaning what drawing code needs.
See also
GetMaxY, InitGraph, ScreenWidth
Example
uses graph;
InitGraph (100, 50, 'grid', False);
var Columns := 0;
for var X := 1; X <= GetMaxX (); X := X + 1 do
Columns := Columns + 1;
System.WriteLn (Columns);
CloseGraph ();
Shell
100
GetMaxY
function — unit graph
Function
Returns the highest Y a program can draw to — the window's height.
Declaration
function GetMaxY () : Integer;
Remarks
Everything said of GetMaxX holds here, for rows — including that the answer is the opened window's, which matters most under fullscreen on macOS, where the menu bar stays and the window is short of the desktop's full height.
Raises Graph is not open. when there is no window.
See also
GetMaxX, InitGraph, ScreenHeight
Example
See GetMaxX and InitGraph, which show both.
GetPixel
function, alias of ViewPort.GetPixel — unit graph
Function
The color of one pixel of a viewport.
Declaration
function GetPixel (V : ViewPort, X : Integer, Y : Integer) : Integer;
Remarks
An alias of the method: GetPixel (V, …) is V.GetPixel (…).
The read PutPixel writes, and the only way to ask what a surface already holds. Coordinates are the viewport's own, counting from 1.
⚠️ Transparent and Black are different answers. A pixel painted black is opaque and answers Black; a pixel never painted answers Transparent and shows whatever surface lies beneath it. Nothing else on a stack of surfaces could tell paint from the gap in it.
A position off the viewport answers Transparent rather than raising, the edge being the clip here exactly as it is for PutPixel.
The value is what was written, not what the screen finally shows: a pixel of a viewport that some other surface covers still answers its own color.
Raises CloseGraph has closed this surface. once the window it belongs to has gone.
See also
Colors, FloodFill, PutPixel, ViewPort
Example
uses graph;
InitGraph (640, 480, 'read', False);
var V := ViewPort (50, 50, 40, 30, 1);
PutPixel (V, 1, 1, White);
PutPixel (V, 2, 1, Black);
System.WriteLn (GetPixel (V, 1, 1) = White);
System.WriteLn (GetPixel (V, 2, 1) = Black); // paint, and opaque
System.WriteLn (GetPixel (V, 3, 1) = Transparent); // never painted
System.WriteLn (GetPixel (V, 41, 1) = Transparent); // past the edge
SetFillStyle (V, SolidFill, Red);
Bar (V, 10, 10, 20, 20);
System.WriteLn (GetPixel (V, 15, 15) = Red);
CloseGraph ();
Shell
true
true
true
true
true
GetTextSettings
functions, aliases of ViewPort.GetTextSettings and GetViewSettings — unit graph
Function
Reads back how a viewport writes text, and where it sits.
Declaration
function GetTextSettings (V : ViewPort) : TextSettings;
function GetViewSettings (V : ViewPort) : ViewSettings;
Remarks
Aliases of the methods, answering a TextSettings or a ViewSettings.
GetTextSettings completes the set begun by GetFillSettings: every pen a viewport holds can now be saved and put back. Its fields are the arguments of SetTextStyle, SetTextJustify and SetUserCharSize.
GetViewSettings answers the corners the viewport occupies in the logical space, inclusive — so X2 is X + W - 1, and Clip is always True. It follows the surface when MoveTo drags it.
Both are snapshots, not views onto the surface.
Raises CloseGraph has closed this surface. once the window has gone.
See also
GetFillSettings, GraphDefaults, SetTextJustify, SetTextStyle, TextSettings
Example
uses graph;
InitGraph (640, 480, 'settings', False);
var V := ViewPort (100, 60, 200, 150, 1);
SetTextStyle (V, 90, 2);
SetTextJustify (V, CenterText, BottomText);
// Save the whole text state before a routine that will change it.
var T := GetTextSettings (V);
System.WriteLn ('direction ', T.Direction, ' size ', T.CharSize);
System.WriteLn ('justify ', T.Horiz, ', ', T.Vert);
SetTextStyle (V, 0, 1);
SetTextJustify (V, LeftText, TopText);
// The fields are the setters' own arguments, so putting it back is two calls.
SetTextStyle (V, T.Direction, T.CharSize);
SetTextJustify (V, T.Horiz, T.Vert);
System.WriteLn ('restored ', GetTextSettings (V).Direction = 90);
// Where the viewport sits, with the far corner worked out: inclusive, so
// X2 is X + W - 1 rather than X + W.
var S := GetViewSettings (V);
System.WriteLn ('corners ', S.X1, ',', S.Y1, ' to ', S.X2, ',', S.Y2);
System.WriteLn ('clipped ', S.Clip);
CloseGraph ();
Shell
direction 90 size 2
justify 1, 0
restored true
corners 100,60 to 299,209
clipped true
GetX
function, alias of ViewPort.GetX — unit graph
Function
Returns the X of a viewport's pen.
Declaration
function GetX (V : ViewPort) : Integer;
Remarks
An alias of the method: GetX (V) is V.GetX ().
In the viewport's own coordinates, counting from 1. A Line leaves the pen at its far end, so this is where the next LineTo will draw from.
Raises CloseGraph has closed this surface. once the window it belongs to has gone.
See also
Example
See Line, which reads the pen back after drawing.
GetY
function, alias of ViewPort.GetY — unit graph
Function
Returns the Y of a viewport's pen.
Declaration
function GetY (V : ViewPort) : Integer;
Remarks
An alias of the method: GetY (V) is V.GetY ().
Everything said of GetX holds here.
Raises CloseGraph has closed this surface. once the window it belongs to has gone.
See also
Example
See Line.
GotoXY
procedure — unit graph and crt
Function
Moves the cursor to a column and row of the grid.
Declaration
procedure GotoXY (Col : Integer, Row : Integer); // the screen
procedure GotoXY (W : Window, Col : Integer, Row : Integer); // that window
Remarks
⚠️ One-based, storybook: the top-left cell is 1, 1 and the bottom-right is TextCols (), TextRows () — the count is the last index, and no cell coordinate ever carries a minus one. The whole screen counts from 1, pixels included, as Turbo Pascal's text mode and every terminal since have had it; the one seam is that a cursor column meets the language's 0-based strings as Text[Col - 1].
A window has the same verb: GotoXY (W, Col, Row) is an alias of W.GotoXY, moving that window's own cursor within its own cells.
A position off the grid raises GotoXY is off the grid. rather than being clamped or ignored — the cursor is always somewhere real, and a wrong computation is caught where it happened.
Raises Graph is not open. without a window.
See also
Example
uses graph;
InitGraph (320, 200, 'goto', False);
GotoXY (10, 5);
System.WriteLn (WhereX ());
System.WriteLn (WhereY ());
CloseGraph ();
Shell
10
5
GraphDefaults
procedure, alias of ViewPort.GraphDefaults — unit graph
Function
Puts every pen of a viewport back the way a fresh one holds them.
Declaration
procedure GraphDefaults (V : ViewPort);
Remarks
An alias of the method. It resets the drawing color, the line style and thickness, the fill pattern and color, the background, the write mode, the text turn, size and justification, and the pen and free-text positions — everything the setters set.
⚠️ It erases nothing, which is Turbo Pascal's behavior too. Clear is what erases; this is about how the next stroke will look, not about what is already drawn.
Nor does it touch what the surface is — its place in the stack, its size, its Alpha, or where MoveTo put it. Those are the object rather than the pens.
It is per surface, as every pen here is. Turbo Pascal's was global because its pens were.
Raises CloseGraph has closed this surface. once the window has gone.
See also
Clear, GetFillSettings, GetTextSettings, ViewPort
Example
uses graph;
InitGraph (640, 480, 'defaults', False);
var V := ViewPort (50, 50, 150, 100, 1);
SetFillStyle (V, SolidFill, Red);
Bar (V, 1, 1, 150, 100);
SetColor (V, Yellow);
SetLineStyle (V, DashedLn, 0, 5);
SetTextStyle (V, 90, 3);
GraphDefaults (V);
// Every pen back the way a fresh viewport holds them.
System.WriteLn ('color ', GetColor (V) = White);
System.WriteLn ('line ', GetLineSettings (V).Thickness = NormWidth);
System.WriteLn ('text ', GetTextSettings (V).Direction = 0);
// But the picture is untouched -- Clear is what erases.
System.WriteLn ('picture ', GetPixel (V, 20, 20) = Red);
CloseGraph ();
Shell
color true
line true
text true
picture true
HighVideo
procedure — unit graph and crt
Function
Brightens the ink celled text draws with.
Declaration
procedure HighVideo (); // the screen
procedure HighVideo (W : Window); // that window
Remarks
HighVideo (W) is an alias of W.HighVideo, brightening that window's ink alone; LowVideo and NormVideo likewise.
A dim palette color becomes its bright partner — Blue to LightBlue, Red to LightRed — and a bright one stays itself, which is the idempotence Turbo Pascal's intensity bit had. The famous odd couple is preserved: Brown's bright partner is Yellow, because the original adapter's brown was a special circuit and the bright version of that slot came out yellow.
⚠️ Off the palette there is no intensity bit, so any other RGB moves halfway toward white — and calling again moves it further, which repeated LowVideo mirrors toward black. A 16-color idea, read honestly in 24 bits.
The background is never touched; NormVideo restores both.
See also
Colors, LowVideo, NormVideo, TextColor
Example
uses graph;
InitGraph (640, 480, 'video', False);
TextColor (Brown);
HighVideo ();
Write ('now yellow');
NormVideo ();
WriteLn (' and back to normal');
System.WriteLn (WhereY ());
CloseGraph ();
Shell
2
Image
class — unit graph
Function
A rectangle of pixels lifted off a surface.
Declaration
constructor Image (W : Integer, H : Integer);
W, H : Integer the size in pixels
Bits : Buffer the pixels, four bytes each, row by row
Remarks
Turbo Pascal's image buffer was an untyped block: the caller sized it with ImageSize, allocated it with GetMem, passed it to GetImage to be filled, and remembered its dimensions separately. This carries its own size and its own storage, so GetImage answers one ready to use.
⚠️ An image belongs to no surface once lifted. It can be put onto the viewport it came from, onto another, or onto the same one repeatedly — see PutImage.
The pixels are the surface's own, transparency included: a region that was partly unpainted comes back partly unpainted, which is what lets CopyPut restore exactly what was taken.
Constructing one directly gives a transparent rectangle, which is occasionally useful as a scratch surface; the usual source is GetImage.
See also
GetImage, ImageSize, PutModes, ViewPort
Example
See GetImage.
ImageSize
function — unit graph
Function
The bytes an image of a rectangle would occupy.
Declaration
function ImageSize (X1 : Integer, Y1 : Integer, X2 : Integer,
Y2 : Integer) : Integer;
Remarks
Four bytes to the pixel, the corners inclusive.
⚠️ It is no longer a step on the way to GetImage. In Turbo Pascal it could not be skipped — the caller sized a block with it, allocated that block, and only then lifted an image into it. An Image carries its own storage, so this answers a question rather than granting permission: what a region will cost, which is worth knowing when the region is large or there are many of them.
It takes no surface and needs no open window, being arithmetic on four numbers.
Turbo Pascal answered a Word and so could not describe an image past 64K, which is a 128 by 128 square in sixteen colors. The Integer here is unbounded.
Raises ImageSize wants X2 >= X1 and Y2 >= Y1.
See also
Example
See GetImage.
InFile
class — unit file
Function
A file open for reading, a line or a run of bytes at a time.
Declaration
constructor InFile (Path : String);
function ReadLine () : String the next line, no terminator
function AtEnd () : Boolean nothing left to give
function ReadBytes (Into : Any, Offset : Integer,
Count : Integer) : Integer
function Position () : Integer bytes from the beginning
procedure Seek (Offset : Integer) move the next read
function Size () : Integer bytes the file holds
procedure Close () released, and idempotent
Remarks
The streaming half of the unit, and the primitive the whole-file routines are built on rather than a parallel way of doing the same thing — ReadAll reads through one of these. Reach for it directly when a file will not fit in memory, when the input is a pipe whose size cannot be known, or when the work is done line by line and there is no reason to hold the rest.
A reader fills a window of 65536 bytes from the operating system and answers lines out of it, so the cost of a line is a scan rather than a system call.
ReadLine takes a carriage return before the newline as part of the newline, so a file written on Windows reads the same as one written here. A final line with no terminator is still a line, and a trailing newline does not invent an empty one after it. ⚠️ That is exactly the rule ReadLines follows, and the two must not disagree — a test asserts they answer the same lines for a file ending with a newline, ending without one, holding a carriage return pair, holding one bare newline, and empty. Past the last line it raises ReadLine: at end of file., so a loop that forgets AtEnd fails rather than spinning on empty strings.
AtEnd asks the operating system when its window is spent, so it is the honest answer rather than a guess from the size — which is what makes it right for a pipe.
ReadBytes is the binary half. It fills Into, a Buffer, starting at Offset, and answers 0 at end of file rather than raising. The offset is what lets a caller fill a growing buffer across several reads, which is how ReadAll is built on this.
Position, Seek and Size index by byte, not by line and not by record — there being no sizeof in this language, so no width the unit could assume. For records indexed by record, see RecordFile.
⚠️ Position is where the CALLER is, not where the handle is. A reader takes 65536 bytes from the operating system at a time, so the handle runs ahead by whatever is still in its window; Position subtracts that. And Seek discards the window, or the next read would answer bytes from where the reader used to be.
⚠️ None of the three works on a pipe, which can only go forwards. Each raises <Member>: this file cannot be positioned. — or … measured. for Size — rather than letting a -1 read as "position zero".
Close may be called more than once, the second doing nothing. That is the bargain Buffer.Free and the core's TextFile.Close already make [RT-023]: a handler releases on the way out without knowing how far the program got, which matters because the language has no try/finally. Every other member of a closed reader raises <Member>: the file is closed.
Raises InFile: cannot open '<Path>'. when the file is absent, is a directory, or cannot be opened. ⚠️ A directory is refused rather than read as empty — fopen succeeds on one, so this is a check the unit makes, and ReadAll makes the same one so that the two agree about what is readable.
See also
OutFile, AppendFile, ReadAll, ReadLines
Example
uses file;
WriteAll ('mixed.txt', 'unix' + #10 + 'windows' + #13 + #10 + 'no newline');
var F := InFile ('mixed.txt');
while not F.AtEnd () do WriteLn ('[', F.ReadLine (), ']');
F.Close ();
F.Close (); // allowed, and does nothing
Erase ('mixed.txt');
Shell
[unix]
[windows]
[no newline]
Bytes rather than lines, and what a closed reader says:
uses file;
WriteAll ('four.bin', 'ABCD');
var F := InFile ('four.bin');
var Dst := Buffer (4);
WriteLn (F.ReadBytes (Dst, 0, 4));
WriteLn (Dst[0], ' ', Dst[3]);
WriteLn (F.ReadBytes (Dst, 0, 4)); // nothing left
F.Close ();
try
F.ReadLine ();
except on E : String do
WriteLn (E);
end
Erase ('four.bin');
Shell
4
65 68
0
ReadLine: the file is closed.
Infinity
constant — unit math
Function
The positive infinity, as a Double.
Declaration
const Infinity := 1.0 / 0.0;
Remarks
A real value rather than a spelling: an overflowing operation answers it, and so does dividing a non-zero value by zero. 1.0 / 0.0 is Infinity rather than a raise — only div and mod refuse a zero divisor.
There is no separate constant for the negative infinity. -Infinity is it, and compares and renders as expected.
It is ordered above every finite Double, which makes it the right seed for a running minimum — the first value compared always replaces it. -Infinity seeds a running maximum the same way.
Unlike NaN, it compares usefully: X = Infinity is a sound test. IsInfinite says it more plainly and catches both signs at once.
Note that Infinity - Infinity is NaN, as is Infinity * 0.0.
See also
IsInfinite, IsNaN, Max, Min, NaN
Example
uses math;
WriteLn (Infinity);
WriteLn (-Infinity);
WriteLn (1.0E300 * 1.0E300 = Infinity);
// Seeded with Infinity, so the first value always replaces it.
var Smallest := Infinity;
for var V in [3.5, -1.25, 9.0] do
Smallest := Min (Smallest, V);
WriteLn (Smallest);
Shell
Infinity
-Infinity
true
-1.25
InitCrt
procedures — unit crt
Function
Opens and closes the terminal screen.
Declaration
procedure InitCrt ();
procedure CloseCrt ();
Remarks
InitCrt takes nothing, where InitGraph takes a size and a title: a terminal already has both, and neither is this program's to choose. TextCols and TextRows answer what it actually is.
It puts the terminal into character-at-a-time mode so ReadKey can work, and onto its alternate screen, so whatever was on the terminal before comes back when the program finishes.
⚠️ CloseCrt gives the terminal back as it was found, and is worth calling from an exception handler as well as at the end — a program that dies without it leaves the terminal in raw mode, which the shell's reset fixes.
Both are idempotent: opening twice changes nothing and closing twice is harmless. CloseCrt invalidates every surface, so a method called on one afterward raises CloseCrt has closed this surface.
Raises Crt is not open. from any verb used before InitCrt.
See also
Crt, IsTerminal, TextCols, Window
Example
uses crt;
InitCrt ();
// The screen is the terminal's own size, asked afresh rather than fixed --
// so this is whatever window the program was run in.
var Cols := TextCols ();
var Rows := TextRows ();
TextBackground (Blue);
TextColor (Yellow);
ClrScr ();
GotoXY (3, 2);
Write ('Hello from crt');
// A window of its own, over the screen, with its own cursor and colors.
var W := Window (5, 4, 30, 8, 1);
W.TextBackground (Red);
W.TextColor (White);
W.Clear ();
W.GotoXY (2, 2);
W.Write ('and from a Window');
Show ();
// Nothing above reached the terminal, because this run is piped. Everything
// composited all the same, which is what the screen can be read back from.
CloseCrt ();
System.WriteLn ('screen was ', Cols, ' by ', Rows);
System.WriteLn ('a terminal: false, so nothing was emitted');
Shell
screen was 80 by 25
a terminal: false, so nothing was emitted
InitGraph
procedure — unit graph
Function
Opens the graphics window.
Declaration
procedure InitGraph (Width : Integer, Height : Integer, Title : String, Fullscreen : Boolean);
Remarks
The window is Width by Height pixels, centered on the desktop, with Title in its title bar — Unicode included. It opens cleared to black.
With Fullscreen true the window instead covers the desktop at the desktop's own resolution, and Width and Height are not used. This is the borderless kind of fullscreen: it changes no display mode, and cannot leave the screen in one if the program dies. On macOS the menu bar stays, so the fullscreen window is the desktop's width but can be short of its height.
The size asked for and the size received can differ — fullscreen is the obvious case — so GetMaxX and GetMaxY report what actually opened rather than echoing the request.
Turbo Pascal's InitGraph took a driver, a mode and a path to BGI files; all three existed to pick a video card and are gone. Failure raises, carrying SDL's own message, rather than setting a result code for GraphResult to fetch — there is no GraphResult.
Raises Graph is already open. for a second call before CloseGraph, and InitGraph needs a positive size. for a Width or Height of zero or less.
The unit reaches SDL2 by its Homebrew path, so as written it wants brew install sdl2.
See also
CloseGraph, GetMaxX, GetMaxY, ScreenWidth
Example
uses graph;
InitGraph (640, 480, 'My Program', False);
System.WriteLn (GetMaxX ());
System.WriteLn (GetMaxY ());
CloseGraph ();
Shell
640
480
Insert
extension function — unit strings
Function
Returns its argument with another string placed at a given index.
Declaration
extension function Insert (S : String, What : String, At : Integer) : String;
Remarks
⚠️ The argument order is not Turbo Pascal's. That Insert took the inserted text first and the target second. An extension's receiver is its first parameter, so the string being inserted into has to come first here — which is also the order that makes S.Insert (' and ', 4) readable. An order that could not be called as a method would have been the odder choice.
At is a 0-based index. Zero prepends, and an At at or past the end appends, so the routine is total over every index as Delete is. Inserting the empty string answers S unchanged.
A negative At raises.
Both spellings work: Insert (S, 'XY', 2) and S.Insert ('XY', 2).
Raises Insert needs a position of zero or more. for a negative At.
See also
Example
uses strings;
WriteLn ('abcdef'.Insert ('--', 3));
WriteLn (Insert ('2026', '-10-24', 4));
// Zero prepends, and a position past the end appends.
WriteLn ('center'.Insert ('[', 0).Insert (']', 99));
Shell
abc--def
2026-10-24
[center]
InstallUserFont
procedure — unit graph
Function
Installs a glyph file as the font all text draws with.
Declaration
procedure InstallUserFont (Path : String);
Remarks
The format is a cell font, one glyph per line: a codepoint, a separator, and hex rows. A : separator carries ink — one bit per pixel, or one byte of coverage per pixel when the file opens with a # gray8 header — and a + separator carries a picture, RRGGBBAA per pixel, which is how emoji arrive in their own colors. A glyph's width is the length of its row data, so a CJK glyph is simply twice as wide as a Latin one and the format needs no width table.
The library ships two:
graphfont.hex | antialiased coverage with emoji; installed by default the first time text draws |
romfont.hex | one bit per pixel — what a 1980s character ROM held |
The default's coverage is all printable ASCII plus a set of Turkish, Greek, Chinese, Korean and Spanish glyphs and a handful of emoji. The example repository's makefont.py generates files in this format from any font the machine has, which is how coverage grows.
A path resolves against the working directory first, and then against the directory ALGOL24_LIB names if it is set — which is how a library installed somewhere else keeps its own glyph files reachable. The working directory wins, so a font beside the program always beats an installed one of the same name, and a run with the variable unset behaves exactly as it did before. A new font replaces the old entirely; a font that cannot be opened leaves the old one installed and raises InstallUserFont: cannot open '...'., naming the path given rather than the places searched.
In Turbo Pascal this registered a .CHR stroked-font file for SetTextStyle to select later; here the glyph file itself is the font, so installing is selecting.
See also
Example
uses graph;
InitGraph (400, 200, 'fonts', False);
OutTextXY (10, 10, 'antialiased, with emoji');
InstallUserFont ('romfont.hex');
OutTextXY (10, 60, 'one bit per pixel');
CloseGraph ();
System.WriteLn ('two fonts, one window');
Shell
two fonts, one window
Int
function — unit math
Function
Returns the integer part of its argument, as a Double.
Declaration
function Int (X : Double) : Double;
Remarks
This is Trunc without the conversion — the same truncation toward zero, but the answer stays a Double. Int (3.7) is 3.0 where Trunc (3.7) is 3, and that difference is the whole reason both exist.
Truncation is toward zero, so Int (-3.7) is -3.0 rather than -4.0.
Nothing is being converted, so each infinity and NaN answers itself rather than raising — the two arguments Trunc refuses. On every finite Double the two agree, each in its own return type.
A Double keeps its sign through truncation, so a value between 0 and -1 answers negative zero: Int (-0.9) renders as -0.0. It compares equal to 0.0, so only the rendering — or the sign of 1.0 / … — tells them apart.
libm's trunc is exactly this function, and declaring it with the return type C really gives it is all it takes.
See also
Example
uses math;
WriteLn (Int (3.7));
WriteLn (Int (-3.7));
WriteLn (Int (1.0E300));
Shell
3.0
-3.0
1.0E300
IsDaylightSaving
function — unit time
Function
Returns whether the host says daylight saving was in force at a given moment.
Declaration
function IsDaylightSaving (Epoch : Double) : Boolean;
Remarks
Takes a moment rather than answering a constant, for the same reason UtcOffset does: whether saving applies is a fact about a date.
Never raises. A zone that does not observe daylight saving and a zone that could not be read both answer False — the host can report "unknown", and that is folded into False rather than invented into a third state the unit would have to carry.
See also
Example
uses time;
// Which answer is right depends on the host's zone, so what is printed is the
// thing that is true everywhere: it is a Boolean for any moment.
var Winter := IsDaylightSaving (1704067200.0);
var Summer := IsDaylightSaving (1719792000.0);
WriteLn (Winter = True or Winter = False);
WriteLn (Summer = True or Summer = False);
Shell
true
true
IsInfinite
function — unit math
Function
Returns True when its argument is either infinity.
Declaration
function IsInfinite (X : Double) : Boolean;
Remarks
Both signs answer True.
⚠️ A NaN answers False. It is not a number, but it is not an infinity either, and keeping the two apart is why there are two predicates rather than one. A value is exactly one of NaN, infinite, or finite, and the three cases are exclusive and exhaustive — which is what makes them safe to branch on.
Infinity compares equal to itself, so this could be written X = Infinity or X = -Infinity at the call site. The predicate says it more plainly and cannot be got half right.
See also
Example
uses math;
WriteLn (IsInfinite (1.0 / 0.0));
WriteLn (IsInfinite (-1.0 / 0.0));
WriteLn (IsInfinite (1.0E300 * 1.0E300));
WriteLn (IsInfinite (1.7976931348623157E308));
WriteLn (IsInfinite (Sqrt (-1.0)));
Shell
true
true
true
false
false
IsNaN
function — unit math
Function
Returns True when its argument is not a number.
Declaration
function IsNaN (X : Double) : Boolean;
Remarks
⚠️ This is the only test that works. A NaN is the one value not equal to itself, and every comparison against it is false — so X = NaN answers False even when X is a NaN, and X <> NaN answers True for every X including a NaN. Neither says what was meant, and both look entirely reasonable.
A NaN arrives from an operation with no answer rather than from no value: Sqrt of a negative, Ln of a negative, zero divided by zero, one infinity subtracted from another, or Infinity * 0.0.
Note that AssertNear already refuses a NaN, so a test need not guard for one separately.
See also
Example
uses math;
WriteLn (IsNaN (Sqrt (-1.0)));
WriteLn (IsNaN (0.0));
WriteLn (IsNaN (Infinity));
// The comparison a reader reaches for first, and why it cannot be used.
var Bad := Sqrt (-1.0);
WriteLn (Bad = NaN);
WriteLn (IsNaN (Bad));
Shell
true
false
false
false
true
IsTerminal
function — unit crt
Function
Whether this screen is painting a real terminal.
Declaration
function IsTerminal () : Boolean;
Remarks
False when standard output is a file or a pipe.
⚠️ Everything works either way. The surfaces composite, the cursor moves, the cells take their colors — only the emitting is skipped. That is what lets a program's own output stay clean when it is piped, and what lets this unit's tests read a finished screen back without a byte reaching stdout.
It is worth asking before deciding to wait for a key: with no terminal none can arrive, so ReadKey answers KeyClose at once and KeyPressed is always False. A program that would otherwise loop until a keypress should ask this first.
if IsTerminal () then ReadKey ();
Raises Crt is not open. before InitCrt.
See also
Crt, InitCrt, KeyPressed, ReadKey
Example
uses crt;
InitCrt ();
// Everything works whether or not there is a terminal to paint: the screen
// composites either way, and only the emitting is skipped.
var Live := IsTerminal ();
TextColor (LightCyan);
GotoXY (1, 1);
Write ('composed either way');
// There can be no keys without a terminal, so ReadKey answers KeyClose at
// once rather than waiting for something that cannot come.
var Waiting := KeyPressed ();
var K := ReadKey ();
CloseCrt ();
System.WriteLn ('a terminal: ', Live);
System.WriteLn ('key waiting: ', Waiting);
System.WriteLn ('ReadKey gave: ', K = KeyClose);
Shell
a terminal: false
key waiting: false
ReadKey gave: true
Join
extension function — unit strings
Function
Returns the members of a List written one after another with a separator between them.
Declaration
extension function Join (L : List, By : String) : String;
Remarks
The receiver is a List rather than a String, this being the one routine in strings that answers text instead of taking it. Both spellings work, as they do for every extension: Join (L, ', ') and L.Join (', ') are the same call.
Members go through Str, so a List of Integers joins as readily as a List of String, and a class carrying a ToString joins as that.
An empty List answers the empty string and a List of one answers that member alone, in both cases without consulting By. An empty By is legitimate and concatenates.
Join undoes Split for every string and every separator, because Split keeps the empty pieces.
Never raises.
See also
Example
uses strings;
var Names := List ();
Names.Add ('Ada');
Names.Add ('Grace');
Names.Add ('Alan');
WriteLn (Names.Join (', '));
WriteLn (Join (Names, ' and '));
var Numbers := List ();
Numbers.Add (1);
Numbers.Add (2);
Numbers.Add (3);
WriteLn (Numbers.Join ('+'));
Shell
Ada, Grace, Alan
Ada and Grace and Alan
1+2+3
KeyPressed
function — unit graph and crt
Function
Returns True when a key is waiting.
Declaration
function KeyPressed () : Boolean;
Remarks
In crt, a screen that is not a terminal has no keys at all, so this is always False there. See IsTerminal.
Neither consumes the key nor blocks; ReadKey answers it.
Polling this in a loop keeps the blink phase beating — the poll presents when a frame is due — so while not KeyPressed do animates a screen the way the era's programs did. When the loop has nothing else to do, ReadKey alone is the better idle, since it sleeps between looks.
Raises Graph is not open. without a window.
See also
Example
See ReadKey, which shows the empty queue answered; examples/keys.a24 echoes every key as it arrives.
Keys
constants — unit graph and crt
Function
The keys that are not characters, each as one Char of its own.
Declaration
const KeyUp := #57344; const KeyF1 := #57360; const KeyF7 := #57366;
const KeyDown := #57345; const KeyF2 := #57361; const KeyF8 := #57367;
const KeyLeft := #57346; const KeyF3 := #57362; const KeyF9 := #57368;
const KeyRight := #57347; const KeyF4 := #57363; const KeyF10 := #57369;
const KeyHome := #57348; const KeyF5 := #57364; const KeyF11 := #57370;
const KeyEnd := #57349; const KeyF6 := #57365; const KeyF12 := #57371;
const KeyPgUp := #57350;
const KeyPgDn := #57351; const KeyClose := #57384;
const KeyInsert := #57352;
const KeyDelete := #57353;
Remarks
Values in Unicode's private-use area, so each special key is an ordinary Char and if ReadKey () = KeyUp reads as it should. Enter, Escape, Tab and Backspace are not here because they never needed to be: they arrive as their real characters, #13 #27 #9 #8, as they always did.
KeyClose is the window's close button, delivered through the same stream — a window is part of this machine, and a program's one input loop should hear it.
See also
Example
See ReadKey.
Line
procedure, alias of ViewPort.Line — unit graph
Function
Draws a straight line on a viewport.
Declaration
procedure Line (V : ViewPort, X1 : Integer, Y1 : Integer, X2 : Integer, Y2 : Integer);
Remarks
An alias of the method: Line (V, …) is V.Line (…).
Draws between two points and leaves the pen at the far end, so a series is PenTo once and LineTo after — which is how the chart in examples/ide.a24 is plotted.
Coordinates are the viewport's own, counting from 1, and its edges are the clip: a line running far outside is drawn for the part that lands and discarded for the rest, never raising.
The current SetLineStyle patterns it and thickens it, and SetColor colors it. Drawing does not appear until something presents; Show is that.
Raises CloseGraph has closed this surface. once the window it belongs to has gone.
See also
LineRel, LineStyles, LineTo, PenTo, Rectangle, SetColor
Example
uses graph;
InitGraph (640, 480, 'lines', False);
var V := ViewPort (100, 100, 400, 300, 1);
// A solid axis, then a dashed thick series plotted point to point.
SetColor (V, LightGray);
Line (V, 40, 20, 40, 260);
Line (V, 40, 260, 380, 260);
SetColor (V, LightGreen);
SetLineStyle (V, DashedLn, 0, ThickWidth);
PenTo (V, 40, 200);
LineTo (V, 140, 90);
LineTo (V, 240, 160);
LineTo (V, 380, 40);
SetColor (V, Yellow);
SetLineStyle (V, SolidLn, 0, NormWidth);
Rectangle (V, 40, 20, 380, 260);
Show (V);
// The pen is where the last LineTo left it: Rectangle does not move it.
System.WriteLn (GetX (V));
System.WriteLn (GetY (V));
System.WriteLn (GetColor (V) = Yellow);
CloseGraph ();
Shell
380
40
true
LineRel
procedure, alias of ViewPort.LineRel — unit graph
Function
Draws from a viewport's pen by a displacement.
Declaration
procedure LineRel (V : ViewPort, DX : Integer, DY : Integer);
Remarks
An alias of the method: LineRel (V, …) is V.LineRel (…).
A displacement where LineTo takes a destination; the pen ends at the far end either way. PenRel is the same move without drawing.
Raises CloseGraph has closed this surface. once the window it belongs to has gone.
See also
Example
See Line.
LineStyles
constants — unit graph
Function
The line styles SetLineStyle takes, and the two thicknesses.
Declaration
const SolidLn := 0; const NormWidth := 1;
const DottedLn := 1; const ThickWidth := 3;
const CenterLn := 2;
const DashedLn := 3;
const UserBitLn := 4;
Remarks
A style is a sixteen-bit pattern walked along the line, one bit to the pixel and repeating: a set bit paints, a clear one skips. The four named patterns are this library's own — Turbo Pascal's exact bits were a BGI implementation detail rather than a promise — and UserBitLn says the pattern comes from the caller's own Pattern argument instead.
The thicknesses are Turbo Pascal's two names for 1 and 3. They are ordinary numbers, and SetLineStyle accepts any positive thickness, so a 7-pixel rule needs no constant.
See also
Example
See Line; examples/ide.a24 shows all five styles and three thicknesses side by side.
LineTo
procedure, alias of ViewPort.LineTo — unit graph
Function
Draws from a viewport's pen to a point.
Declaration
procedure LineTo (V : ViewPort, X : Integer, Y : Integer);
Remarks
An alias of the method: LineTo (V, …) is V.LineTo (…).
The pen ends where the line does, so successive calls plot a series — the idiom a chart is drawn with. PenTo is the same move without drawing.
Raises CloseGraph has closed this surface. once the window it belongs to has gone.
See also
Example
See Line, which plots four points this way.
Ln
function — unit math
Function
Returns the natural logarithm of its argument.
Declaration
function Ln (X : Double) : Double;
Remarks
Ln (0.0) answers -Infinity and a negative argument answers NaN. Neither raises — both come from libm rather than from a check here — so a program that cares must test the argument or the result itself. NaN is not equal to itself, which is the usual way to detect it.
A foreign declaration onto libm's log. The name is Ln rather than C's Log because log is ambiguous across languages — natural in C, base ten in others — where Ln can only mean one thing.
See also
Example
uses math;
WriteLn (Ln (1.0));
WriteLn (Ln (Exp (1.0)));
WriteLn (Ln (0.0));
Shell
0.0
1.0
-Infinity
LoadSound
functions and procedures — unit sound
Function
Plays a sound effect from an audio file.
Declaration
function LoadSound (Path : String) : Integer;
function PlaySound (Clip : Integer, Volume : Integer) : Boolean;
function SoundLength (Clip : Integer) : Integer;
function SoundPlaying (Clip : Integer) : Boolean;
procedure StopSounds ();
procedure FreeSound (Clip : Integer);
procedure CloseSound ();
Remarks
Neither Turbo Pascal's nor BASIC's — a sound effect from a file, mixed under whatever else is sounding.
⚠️ WAV only. The unit plays through SDL2, which carries one decoder, where the CoreAudio backend it replaced read AIFF, CAF, MP3 and M4A as well through the system's codecs. That breadth was the price of working on one operating system alone, and the trade was made the other way deliberately; SDL2_mixer would buy it back at the cost of a second dependency and is not here.
Any WAV is read whatever its rate, width or channel count, and converted once to the mixer's own format — float32 mono at 44100 — so a 22050 Hz 16-bit stereo recording loads as readily as one that already matches.
The file is decoded once, up front, so playing it later costs only the mixing, which is what a sound effect needs and why this is not done per play. Decoding asks nothing of the audio device, so it works under ALG_SOUND=dummy and before anything has made a noise.
⚠️ PlaySound returns at once. The effect plays while the program carries on, which is the whole point of one; SoundLength says how long it will take if that matters. Sixteen may sound at a time, and a seventeenth is dropped rather than cutting one short, answering False.
It also answers False when nothing can be heard at all — see SoundAvailable — since there is no voice to start on a device that was never opened. LoadSound still decodes in that case, so SoundLength is real either way.
Volume is 0 to 255 and is that sound's own, not the tone's.
⚠️ NoSound does not stop these, a sound effect not being a note. StopSounds silences every effect and leaves the tone; CloseSound stops everything and closes the device.
Sixty-four may be loaded at once. FreeSound gives one back and stops anything playing it; the handle is not a sound afterward, and using it raises.
Raises LoadSound could not read <path>. for a file that is missing, is not audio, is longer than ten minutes, or when sixty-four are already loaded; and <verb> wants a sound from LoadSound. for a handle that is not one.
See also
Example
uses sound;
// A WAV, decoded once up front, so playing it later costs only the mixing.
// beep.wav ships with the library: 300 ms at 22050 Hz in 16-bit mono, which
// is not the mixer's format -- so loading it converts.
var Ping := LoadSound ('beep.wav');
System.WriteLn ('length: ', SoundLength (Ping), ' ms (a real decode)');
System.WriteLn ('sounding: ', SoundPlaying (Ping));
// Returns at once -- a sound effect plays while the program carries on, which
// is the whole point of one. It answers False here because this run is
// silent; see SoundAvailable.
var Started := PlaySound (Ping, 200);
System.WriteLn ('started: ', Started, ' (audible: ', SoundAvailable (), ')');
FreeSound (Ping);
// Freed, the handle is not a sound any more.
var Message := '';
try SoundLength (Ping); except on e : String do Message := e; end
System.WriteLn ('freed: ', Message);
CloseSound ();
Shell
length: 300 ms (a real decode)
sounding: false
started: false (audible: false)
freed: SoundLength wants a sound from LoadSound.
Lower
extension function — unit strings
Function
Returns its argument with the ASCII uppercase letters lowered.
Declaration
extension function Lower (S : String) : String;
Remarks
⚠️ This is the core's own ToLower, with the extension spelling added, on the same terms as Upper. ToLower (S) is the same call.
ASCII only, which is the core's decision: every character outside A–Z comes back exactly as it went in, accented letters and emoji included.
Both spellings work: Lower (S) and S.Lower ().
Never raises.
See also
Example
uses strings;
WriteLn (Lower ('SHOUTING'));
WriteLn ('MiXeD'.Lower ());
// ASCII only, on the same terms as Upper.
WriteLn ('CAFÉ'.Lower ());
Shell
shouting
mixed
cafÉ
LowVideo
procedure — unit graph and crt
Function
Dims the ink celled text draws with.
Declaration
procedure LowVideo (); // the screen
procedure LowVideo (W : Window); // that window
Remarks
The mirror of HighVideo: a bright palette color becomes its dim partner and a dim one stays itself; any other RGB moves halfway toward black, again further on each call.
See also
Example
See HighVideo; examples/video.a24 shows the whole palette both ways.
Max
function — unit math
Function
Returns the larger of its two arguments.
Declaration
function Max (A, B);
Remarks
The result is whichever argument was larger, in that argument's own type. A tie answers B, which is visible only when the two differ in type: Max (2, 2.0) is 2.0 and Max (2.0, 2) is 2.
Like Abs, Max is untyped, so its result cannot initialize a variable of a written type. Assigning to a variable whose type was inferred is fine, which is what makes the running-maximum idiom in the example work.
Raises Operands must be numbers. for arguments the comparison cannot take.
See also
Example
uses math;
WriteLn (Min (3, 7));
WriteLn (Max (3, 7));
var Highest := 0;
for var N in [3, 17, 8] do
Highest := Max (Highest, N);
WriteLn (Highest);
Shell
3
7
17
Min
function — unit math
Function
Returns the smaller of its two arguments.
Declaration
function Min (A, B);
Remarks
The result is whichever argument was smaller, in that argument's own type. A tie answers B, on the same reasoning as Max: Min (2, 2.0) is 2.0 and Min (2.0, 2) is 2.
Untyped, with the same consequence for a declared variable as Abs and Max.
Raises Operands must be numbers. for arguments the comparison cannot take.
See also
Example
See Max, which shows both.
MoveTo
procedure, alias of Window.MoveTo and ViewPort.MoveTo — unit graph and crt
Function
Moves a surface, keeping its size.
Declaration
procedure MoveTo (Surface, X : Integer, Y : Integer);
Remarks
crt's takes a Window and nothing else, that unit having no ViewPorts for an untyped surface to choose between.
An alias of both methods: MoveTo (W, …) is W.MoveTo (…).
A Window moves in cells and a ViewPort in the logical space's pixels — each surface in the coordinates it was placed in. Any position is allowed, off the grid included: a surface may be dragged partly or wholly out of view, and what falls outside is clipped at present time.
⚠️ This one takes an untyped surface rather than being declared once per class. Two declarations of one arity would put the choice back on the argument's type, which a gradual type system settles at run time and warns about at every call site — correctly, since it cannot know. Asking is Window inside costs one branch and no noise.
⚠️ MoveTo moves the surface; PenTo moves a viewport's pen. Turbo Pascal spelled the pen's move MoveTo, but a surface is a thing that can itself be moved, and that reading wins the shorter name.
Raises MoveTo wants a Window or a ViewPort. for anything else, and CloseGraph has closed this surface. once the window has gone.
See also
Example
uses graph;
InitGraph (640, 480, 'moveto', False);
var Panel := Window (2, 2, 20, 8, 1);
var Chart := ViewPort (100, 100, 60, 40, 2);
MoveTo (Panel, 30, 5);
MoveTo (Chart, 250, 180);
System.WriteLn (Panel.X1);
System.WriteLn (Panel.X2);
System.WriteLn (Chart.X);
CloseGraph ();
Shell
30
48
250
NaN
constant — unit math
Function
The quiet NaN, as a Double.
Declaration
const NaN := 0.0 / 0.0;
Remarks
Useful for handing back a Double that means nothing, and for feeding a routine under test.
⚠️ It is not useful for comparison, and that is the whole of what makes it awkward. This constant is not equal to itself, and no value is equal to it. X = NaN is always False and X <> NaN is always True, whatever X is. IsNaN is the only way to ask.
It renders as NaN, which is how a NaN shows up in output and in a failed assertion's message.
See also
Example
uses math;
WriteLn (NaN);
WriteLn (NaN = NaN);
WriteLn (NaN <> NaN);
WriteLn (IsNaN (NaN));
Shell
NaN
false
true
true
NormVideo
procedure — unit graph and crt
Function
Restores the ink and background a text mode wakes up in.
Declaration
procedure NormVideo (); // the screen
procedure NormVideo (W : Window); // that window
Remarks
LightGray on Transparent — the defaults InitGraph and TextMode set — which is what Turbo Pascal's NormVideo did with the attribute the program started under. The one of the three that touches the background.
See also
HighVideo, LowVideo, TextBackground
Example
See HighVideo.
Now
functions — unit time
Function
Return the moment now, as a DateTime.
Declaration
function Now () : DateTime;
function UtcNow () : DateTime;
Remarks
Now reads the clock in the host's own time zone and UtcNow without a zone. Both are At and UtcAt applied to clock ().
One call answering one object, where Turbo Pascal's Dos unit had GetDate and GetTime. That split was an artifact of two separate DOS interrupts, and asking twice has a real hazard: the fields could straddle a tick, answering the hour from before midnight and the minute from after. The seven fields here come from one reading.
SetDate and SetTime have no counterpart in this library. Setting the host clock needs root on every system this runs on, so the honest remark for them would be that they always fail.
Raises time: the host could not break down that moment., which no working host provokes.
See also
Example
uses time;
// Now cannot print a fixed answer, so this shows its shape instead.
var M := Now ();
WriteLn (Length (M.Text ()));
WriteLn (M.Year >= 2026);
WriteLn (M.Month >= 1 and M.Month <= 12);
// Both readings are one instant, so their Epoch is identical.
WriteLn (Now ().Epoch <= UtcNow ().Epoch);
Shell
19
true
true
true
Odd
function — unit math
Function
Returns True when its argument is odd.
Declaration
function Odd (N : Integer) : Boolean;
Remarks
N must be an Integer. A Double raises Operands must be integers., because mod refuses one rather than truncating it.
Negative numbers answer correctly. This is worth stating because the obvious implementation does not: mod keeps the sign of its left operand, so -3 mod 2 is -1, and a test written N mod 2 = 1 would answer False for every negative odd number. The test here is <> 0.
The argument is unbounded, so oddness of a number past the machine width is answered as readily as any other.
See also
Example
uses math;
for var N := 1; N <= 5; N := N + 1 do
if Odd (N) then WriteLn (Str (N) + ' is odd');
Shell
1 is odd
3 is odd
5 is odd
OutFile
class — unit file
Function
A file open for writing, emptied first.
Declaration
constructor OutFile (Path : String);
procedure Write (Text : String) as it stands, adding nothing
procedure WriteLine (Text : String) and a newline
procedure WriteBytes (From : Any, Count : Integer)
procedure Flush () push what is buffered
function Position () : Integer bytes from the beginning
procedure Seek (Offset : Integer) move the next write
function Size () : Integer bytes the file holds
procedure Close () flushed, released, idempotent
Remarks
The writing half of the streaming surface. Reach for it when output is produced as the program runs rather than assembled and handed over whole, which is what WriteAll is for.
Opening empties the file — Turbo Pascal's Rewrite rather than its Append. To keep what is there, use AppendFile.
⚠️ There is deliberately no free-function alias for any of these, where nearly every surface verb in graph and crt has one. Those two units both export a free Write that shadows the built-in, and a third would make a bare Write ambiguous in the combinations worth writing — the same collision that keeps Delay out of sound. A method on a receiver collides with nothing. WriteLine is spelled out for the same reason: nobody reading it should have to wonder which unit's WriteLn answered.
WriteLine's terminator is #10 alone, never a carriage return pair, which is what WriteLines also writes — so a file written here reads back the same through InFile or ReadLines on any platform.
WriteBytes takes the bytes from the start of From, a Buffer. A Count of zero or less writes nothing, and nil raises WriteBytes: needs a buffer.
⚠️ Bytes may sit in a buffer until Flush or Close. A program that ends without closing may lose the tail, which is the one real cost of writing this way instead of with WriteAll. Flush makes what was written readable without closing, which is what a long-running program keeping a log wants; Close flushes too, so a program that closes need not call it.
Position, Seek and Size are byte-indexed, as InFile's are. Size counts what is still buffered as well as what has reached the disk, because it asks the handle rather than the path. Seeking back and writing is how a record is replaced in place without rewriting the file — RecordFile is that, done by record index.
Writing past the end leaves a hole, which reads back as zero bytes. That is the operating system's behaviour rather than this unit's choice.
Close may be called more than once, on the same terms as InFile's. Every other member of a closed file raises <Member>: the file is closed.
Raises OutFile: cannot open '<Path>'. when the file cannot be opened for writing.
See also
AppendFile, InFile, WriteAll, WriteLines
Example
uses file;
var O := OutFile ('report.txt');
O.WriteLine ('totals');
O.Write ('42');
O.Flush ();
// Readable while the file is still open.
WriteLn (ReadAll ('report.txt'));
O.Close ();
O.Close (); // allowed, and does nothing
try
O.Write ('more');
except on E : String do
WriteLn (E);
end
Erase ('report.txt');
Shell
totals
42
Write: the file is closed.
Bytes rather than text:
uses file;
var B := Buffer (3);
B[0] := 72; B[1] := 105; B[2] := 33; // H i !
var O := OutFile ('bytes.bin');
O.WriteBytes (B, 3);
O.Close ();
WriteLn (ReadAll ('bytes.bin'));
WriteLn (FileSize ('bytes.bin'));
Erase ('bytes.bin');
Shell
Hi!
3
OutText
procedure — unit graph
Function
Draws text at the current position and advances it by the text's width.
Declaration
procedure OutText (Text : String); // the background
procedure OutText (V : ViewPort, Text : String); // that viewport
Remarks
Successive calls continue one line, which is what the current position exists for. The position starts at the window's top-left corner when InitGraph opens it; OutTextXY neither consults nor moves it.
Nothing wraps: text past the window's edge is clipped, not folded.
Any codepoint the installed font carries will draw — see InstallUserFont for what the shipped default covers. Emoji arrive in their own colors. A codepoint the font lacks advances a blank half-cell rather than raising, so a text with one exotic character still lands. The ink is the background surface's white; a ViewPort's own free text takes the color its SetColor was given.
WriteLn cannot serve here, and it was tried: a unit-defined WriteLn replaces the built-in rather than overloading it, so a program using such a unit would lose console output entirely — WriteLn ('x') answers Expected 2 arguments but got 1. The Turbo Pascal names avoid breaking the console to reach the window.
Raises Graph is not open. without a window.
See also
Example
uses graph;
InitGraph (400, 200, 'text', False);
OutTextXY (10, 10, 'Hello 你好 🙂');
OutText ('one ');
OutText ('line, ');
OutText ('in pieces');
CloseGraph ();
System.WriteLn ('drawn');
Shell
drawn
OutTextXY
procedure — unit graph
Function
Draws text with its top-left corner at X, Y.
Declaration
procedure OutTextXY (X : Integer, Y : Integer, Text : String); // the background
procedure OutTextXY (V : ViewPort, X : Integer, Y : Integer, Text : String); // that viewport
Remarks
The current position is neither consulted nor moved, which is Turbo Pascal's rule and the useful one: placed text is placed, and a following OutText carries on from wherever it was. Pixels count from 1 — 1, 1 is the window's corner — like everything on this screen.
Coordinates may land partly or wholly outside the window; what falls outside is clipped pixel by pixel rather than raising, so a label may slide off an edge gracefully.
Everything said of OutText about fonts, emoji, missing glyphs and ink holds here.
Raises Graph is not open. without a window.
See also
Example
See OutText and InstallUserFont, which place text with it.
PenRel
procedure, alias of ViewPort.PenRel — unit graph
Function
Moves a viewport's pen by a displacement, without drawing.
Declaration
procedure PenRel (V : ViewPort, DX : Integer, DY : Integer);
Remarks
An alias of the method: PenRel (V, …) is V.PenRel (…).
PenTo and PenRel pair with LineTo and LineRel — the same two destinations, one drawing and one not.
Raises CloseGraph has closed this surface. once the window it belongs to has gone.
See also
Example
See Line.
PenTo
procedure, alias of ViewPort.PenTo — unit graph
Function
Moves a viewport's pen to a point, without drawing.
Declaration
procedure PenTo (V : ViewPort, X : Integer, Y : Integer);
Remarks
An alias of the method: PenTo (V, …) is V.PenTo (…).
Where a series of LineTo calls begins. Turbo Pascal spelled this MoveTo, which here moves the viewport itself — see MoveTo. PenTo and PenRel pair with LineTo and LineRel: the same two destinations, one drawing and one not, which is a clarity Turbo Pascal's naming did not have.
Raises CloseGraph has closed this surface. once the window it belongs to has gone.
See also
GetX, Line, LineTo, MoveTo, PenRel
Example
See Line, which begins its series with it.
Pi
constant — unit math
Function
The ratio of a circle's circumference to its diameter.
Declaration
const Pi := 3.141592653589793;
Remarks
The value is the nearest Double to π, and is the same one C's M_PI names, so a computation mixing it with a libm result through Sin, Cos or ArcTan stays consistent.
It is a constant rather than a function, unlike Turbo Pascal's Pi, because nothing here needs it to be a call.
Being the nearest Double and not π, it does not behave like the exact value everywhere — see Cos for the quarter-turn case.
See also
Example
uses math;
var Radius := 3.0;
WriteLn ('circumference: ' + Str (2 * Pi * Radius));
WriteLn ('area: ' + Str (Pi * Sqr (Radius)));
Shell
circumference: 18.84955592153876
area: 28.274333882308138
PieSlice
procedure, alias of ViewPort.PieSlice — unit graph
Function
Fills and outlines a pie slice on a viewport.
Declaration
procedure PieSlice (V : ViewPort, X : Integer, Y : Integer, StartAngle : Integer,
EndAngle : Integer, Radius : Integer);
Remarks
An alias of the method: PieSlice (V, …) is V.PieSlice (…).
The wedge between two angles: filled with the current fill pattern and color, then outlined with the pen and the current line style — the arc, and the two radii closing it to the center.
Angles are Arc's: degrees, zero at three o'clock, counterclockwise, ninety at twelve, and the sweep is the counterclockwise one.
⚠️ A sweep of 360 is the whole disc, and draws no radii. The two would coincide, and a spoke across a full pie is a blemish rather than an edge.
⚠️ Two pens. The wedge is laid in the fill color and edged in the drawing color — which is exactly what a labelled pie chart wants, and what SetFillStyle is separate for. With EmptyFill the slice is outlined and hollow, which is how to draw one without a color.
The pen is not moved.
The fill is drawn by C, as Bar's is, and for the same reason. It asks whether a point lies within the sweep by cross product rather than arctangent — a ray divides the plane, and which side a point falls on answers the question exactly, with no transcendental per pixel and no need for a two-argument ArcTan the library does not have.
Raises PieSlice needs a radius of zero or more. and CloseGraph has closed this surface.
See also
Arc, Circle, GetArcCoords, Sector, SetFillStyle
Example
uses graph;
InitGraph (640, 480, 'pie', False);
var V := ViewPort (60, 40, 400, 400, 1);
// A pie chart: each slice filled in its own color and edged in white.
var Shares := [22, 18, 25, 15, 20];
var Inks := [LightRed, Yellow, LightCyan, LightGreen, LightMagenta];
var At := 0;
SetColor (V, White);
for var I := 0; I < 5; I := I + 1 do
begin
SetFillStyle (V, SolidFill, Inks[I]);
PieSlice (V, 200, 200, At * 36 div 10, (At + Shares[I]) * 36 div 10, 150);
At := At + Shares[I];
end
Show (V);
// The first slice starts at three o'clock and sweeps upward.
System.WriteLn (V.Buf.GetInt ((199 * 340 + 259) * 4) <> 0);
System.WriteLn (GetColor (V) = White);
CloseGraph ();
Shell
true
true
Play
procedure and function — unit sound
Function
Plays a tune written in BASIC's Music Macro Language.
Declaration
procedure Play (MML : String);
function Score (MML : String) : List;
Remarks
What Turbo Pascal never had and BASIC always did: a string that says notes rather than frequencies, and knows what a dotted quaver is worth at 120 beats a minute.
Play ('T120 O4 L8 CDEFGAB O5 C2');
The dialect is GW-BASIC's:
A–G | a note; # or + sharpens it, - flattens it |
On | octave, 0 to 6 — octave 4 holds middle C |
> < | one octave up or down, stopping at the ends |
Ln | the default note length: 1, 2, 4, 8 … 64 |
| n after a note | that note's length, overriding L |
. | dotted — adds half of what came before, and they stack |
Tn | tempo, quarter notes to the minute, 32 to 255 |
Pn, Rn | a rest of that length |
Nn | a note by number, 0 to 84; N0 is a rest |
ML MN MS | legato, normal, staccato |
MF MB | foreground, background |
Spaces are ignored, so a tune may be written in bars, and lower case means the same as upper.
⚠️ Score answers the notes without playing them — a List of [hertz, sounding ms, resting ms], where a hertz of 0 is a rest. That is what makes a tune checkable: it can be asserted note by note with nothing audible. Play performs exactly what Score answers.
⚠️ Articulation changes how much of a note sounds, never how long it takes. MN sounds seven eighths and rests for the last — which is what makes a repeated note audible as two notes — and MS sounds three quarters. The note still occupies its whole length either way, so phrasing never changes the tempo.
⚠️ Play is foreground only. The call takes as long as the tune does, which is what MF meant. MB is accepted and ignored rather than refused, so a listing that asks for background music still plays.
⚠️ A faulty tune plays nothing. The whole string is parsed before a note sounds, so a fault at the end does not play the beginning and then raise.
Octave 4 holding middle C lines the octave numbers up with MIDI and scientific pitch notation. Sources differ on whether GW-BASIC's own octave 4 or octave 3 did; this picks the one a reader today expects.
Raises Play does not know '<c>'., Play wants an octave from 0 to 6., Play wants a length from 1 to 64., Play wants a tempo from 32 to 255., Play wants a note number from 0 to 84., Play wants a letter after M. and Play wants L, N, S, F or B after M.
See also
Example
uses sound;
// Every note of an MML string, without a sound being made: the frequency in
// hertz, how long it sounds, and how long it rests afterward.
for var Bit in ['C', 'C#', 'C-', 'O5C', 'L4C.', 'MS C', 'P4', 'N49'] do
begin
var N := Score (Bit)[0];
System.WriteLn (Bit, ' -> ', N[0], ' Hz, ', N[1], ' ms + ', N[2],
' ms rest');
end
// MN leaves an eighth of every note silent, which is what makes a repeated
// note audible as two notes rather than one long one. The note still occupies
// its whole length, so phrasing never changes the tempo.
for var Mode in ['ML', 'MN', 'MS'] do
begin
var N := Score (Mode + ' T120 L4 C')[0];
System.WriteLn (Mode, ' sounds ', N[1], ' of ', N[1] + N[2], ' ms');
end
Shell
C -> 262 Hz, 437 ms + 63 ms rest
C# -> 277 Hz, 437 ms + 63 ms rest
C- -> 247 Hz, 437 ms + 63 ms rest
O5C -> 523 Hz, 437 ms + 63 ms rest
L4C. -> 262 Hz, 656 ms + 94 ms rest
MS C -> 262 Hz, 375 ms + 125 ms rest
P4 -> 0 Hz, 500 ms + 0 ms rest
N49 -> 262 Hz, 437 ms + 63 ms rest
ML sounds 500 of 500 ms
MN sounds 437 of 500 ms
MS sounds 375 of 500 ms
PutModes
constants — unit graph
Function
How PutImage combines an image with what is already there.
Declaration
const CopyPut := 0; const AndPut := 3;
const XorPut := 1; const NotPut := 4;
const OrPut := 2; const TransparentPut := 5;
Remarks
Turbo Pascal's five, plus one its hardware had no need of.
CopyPut | replaces the rectangle, the image's transparency included |
TransparentPut | lays only the pixels the image painted |
XorPut | combines by exclusive or; twice restores what was there |
OrPut, AndPut | combine by union and intersection |
NotPut | draws the image's colors inverted |
⚠️ TransparentPut is this library's own. Turbo Pascal's images were opaque indices throughout, so the question never arose; a surface here is transparent until painted, and a sprite laid over a background needs the mode that skips what it never painted. CopyPut cannot do it — it would stamp the sprite's unpainted surround over the background.
The five inherited modes combine the whole 32-bit pixel, alpha included. That is what makes XorPut restore exactly — (a xor b) xor b is a whatever the bits mean — and what lets an opaque image show over a transparent surface at all, where combining only the color would leave the alpha at zero and the image invisible.
NotPut is the exception: it inverts the color and keeps the source's alpha, because the inverse of a picture is a picture rather than an absence of one.
See also
Example
See GetImage.
PutPixel
procedure, alias of ViewPort.PutPixel — unit graph
Function
Paints one pixel of a viewport.
Declaration
procedure PutPixel (V : ViewPort, X : Integer, Y : Integer, Color : Integer);
Remarks
An alias of the method: PutPixel (V, …) is V.PutPixel (…).
Coordinates are the viewport's own, counting from 1 — 1, 1 is its top-left corner, not the screen's.
⚠️ A pixel outside the viewport is discarded silently, never raising. The edge is the clip, which is what lets a drawing be written without bounds checks and a viewport be moved without its contents escaping.
The color is written directly and does not use the pen, so SetColor does not affect it. Drawing does not appear until something presents; Show is that.
Raises PutPixel wants a color or Transparent. below Transparent or above White — this member had no color check at all before 0.1.6, and wrote the value straight into the surface — and CloseGraph has closed this surface. once the window it belongs to has gone.
See also
GetPixel, Line, Show, ViewPort
Example
uses graph;
InitGraph (640, 480, 'pixels', False);
var V := ViewPort (50, 50, 40, 30, 1);
PutPixel (V, 1, 1, White);
PutPixel (V, 40, 30, Yellow);
PutPixel (V, 41, 1, Red); // past the edge: clipped, silently
Show (V);
System.WriteLn (GetPixel (V, 1, 1) = White);
System.WriteLn (GetPixel (V, 40, 30) = Yellow);
System.WriteLn (GetPixel (V, 41, 1) = Transparent);
CloseGraph ();
Shell
true
true
true
Random
function — unit random
Function
Returns the next value in the sequence, at least zero and below Bound.
Declaration
function Random (Bound : Integer) : Integer;
Remarks
The short name for RandomInteger, and a pass-through to it — the same draw, not a parallel one.
It names the Integer form rather than the Double one because that is what is reached for: picking an element, rolling a die and choosing a case all want a bounded Integer. RandomReal has no short spelling for the same reason.
⚠️ It is a pass-through rather than a second overload of one name. Turbo Pascal spells both shapes Random, and since 0.1.4 the language would allow it — two arities settle statically and in silence, where 0.1.3 warned at every call site and would have made the unit's commonest call its noisiest. The two names are kept for what is left: a single Random would take its return type from how many arguments it was given, a Double for none and an Integer for one, which is something a reader counts rather than reads. Random and RandomReal say which at the call site.
See also
RandomInteger, RandomReal, SetSeed
Example
uses random;
SetSeed (2024);
for var Roll := 0; Roll < 5; Roll := Roll + 1 do
WriteLn ('die: ' + Str (Random (6) + 1));
Shell
die: 5
die: 6
die: 5
die: 1
die: 4
RandomInteger
function — unit random
Function
Returns the next value in the sequence, at least zero and below Bound.
Declaration
function RandomInteger (Bound : Integer) : Integer;
Remarks
The upper bound is excluded. RandomInteger (6) answers one of 0, 1, 2, 3, 4 or 5, so a die is RandomInteger (6) + 1. Excluding it is what makes the routine compose with a length: L[RandomInteger (L.Length)] is always an element of L.
A bound of zero or less raises RandomInteger needs a bound above zero., having no value it could answer with.
The distribution is as even as 48 bits allow. Beyond a bound of 2^48 the values thin out — there are only 2^48 sequences to draw from however large the bound — and beyond 2^53 the multiplication itself loses precision. Neither limit is reached by any ordinary use, and neither is checked.
See also
Example
uses random;
SetSeed (7);
var Colors := ['red', 'green', 'blue'];
for var I := 0; I < 4; I := I + 1 do
WriteLn (Colors[RandomInteger (Colors.Length)]);
Shell
red
blue
red
red
Randomize
procedure — unit random
Function
Seeds the generator unpredictably, from the clock and the process.
Declaration
procedure Randomize ();
Remarks
Call it once, at the start of a program that wants a different sequence on every run.
⚠️ A program that never calls it gets the same sequence every time. That is deliberate — a program is reproducible by default and becomes unpredictable only where it asks to be — but it does surprise anyone expecting a fresh sequence for free.
The seed is nanosecond time mixed with the process id, not the whole second time would answer. Seconds would give two programs started in the same second identical sequences, and the process id separates two that start within the same nanosecond.
SetSeed undoes it: seeding explicitly after Randomize restores a repeatable sequence, which is how a program can be unpredictable in use and deterministic under test.
See also
Example
uses random;
Randomize ();
// Nothing here is repeatable, which is the point of it -- so all that can be
// shown is that the generator works.
var V := RandomReal ();
WriteLn (V >= 0.0 and V < 1.0);
Shell
true
RandomReal
function — unit random
Function
Returns the next value in the sequence, at least zero and below one.
Declaration
function RandomReal () : Double;
Remarks
Zero may be answered and one never is.
The generator has 48 bits, so the result carries 48 bits of entropy rather than the 53 a Double could hold. That is drand48, carried in the library's own C rather than taken from the host's: POSIX specifies the algorithm exactly, so owning it changes no stream — measured bit-identical against the platform's own over four thousand draws — and it is what lets the unit work where libc has no drand48 at all. A seed answers the same sequence on every platform.
Scale it for a range: Low + RandomReal () * (High - Low) lands in [Low, High). For a whole number use RandomInteger rather than truncating this, which is the same thing said once instead of twice.
See also
Random, RandomInteger, SetSeed
Example
uses random;
SetSeed (1);
WriteLn (RandomReal ());
WriteLn (RandomReal ());
Shell
0.041630344771878214
0.45449244472862915
ReadAll
functions and procedures — unit file
Function
Reads and writes whole text files.
Declaration
function ReadAll (Path : String) : String;
procedure WriteAll (Path : String, Text : String);
procedure AppendAll (Path : String, Text : String);
function Exists (Path : String) : Boolean;
function IsDirectory (Path : String) : Boolean;
function FileSize (Path : String) : Integer;
procedure Erase (Path : String);
procedure Rename (From : String, To : String);
procedure CopyFile (From : String, To : String);
Remarks
⚠️ Whole files, deliberately. There is no handle to hold, no cursor to keep, and nothing to remember to close. That covers everything this library does with files and almost everything a program does with a text file.
The unit owns its own C rather than using the language's TextFile, which exists for the compiler. That is the same bargain math and Sound strike, and it means file can grow without the language changing. It is also the library's first foreign code that builds anywhere — soundffi.c is macOS-only and crtffi.c is POSIX-only, where nothing here is worse than fopen.
Exists never raises: asking about a path that is not there is the question, not a fault. IsDirectory is worth asking separately, because opening a directory as a file succeeds on some systems and then reads nothing — which would look like an empty file rather than a mistake. ReadAll refuses one outright.
An empty file answers an empty String rather than raising.
AppendAll makes the file if it is not there. CopyFile copies a block at a time in the C rather than reading then writing here, so a large file is not held in memory to be moved.
⚠️ A file holding a zero byte is not text, and ReadAll says so rather than answering a truncated String. See DEFECTS.md H-2 for why that check exists and what it protects.
Newlines arrive exactly as the file holds them — ReadLines is what strips carriage returns.
Paths resolve against the working directory.
Raises ReadAll: cannot read '<path>'., ReadAll: '<path>' is not text., FileSize: cannot read '<path>'., WriteAll: cannot write '<path>'., AppendAll: cannot write '<path>'., Erase: cannot remove '<path>'., Rename: cannot rename '<from>'. and CopyFile: cannot copy '<from>'.
See also
Example
uses file;
// Whole files, so there is no handle to hold and nothing to close.
WriteAll ('notes.txt', 'alpha' + #10 + 'beta' + #10 + 'gamma' + #10);
System.WriteLn ('exists: ', Exists ('notes.txt'));
System.WriteLn ('bytes: ', FileSize ('notes.txt'));
var Lines := ReadLines ('notes.txt');
System.WriteLn ('lines: ', Lines.Length);
System.WriteLn ('the last: ', Lines[2]);
// A trailing newline does not invent an empty last line.
AppendAll ('notes.txt', 'delta' + #10);
System.WriteLn ('appended: ', ReadLines ('notes.txt').Length, ' lines');
CopyFile ('notes.txt', 'copy.txt');
System.WriteLn ('copied: ', ReadAll ('copy.txt') = ReadAll ('notes.txt'));
Rename ('copy.txt', 'moved.txt');
System.WriteLn ('moved: ', Exists ('moved.txt'), ' and copy.txt gone: ',
not Exists ('copy.txt'));
Erase ('notes.txt');
Erase ('moved.txt');
System.WriteLn ('cleaned: ', not Exists ('notes.txt'));
Shell
exists: true
bytes: 17
lines: 3
the last: gamma
appended: 4 lines
copied: true
moved: true and copy.txt gone: true
cleaned: true
ReadEvent
functions — unit graph and crt
Function
Takes the next event, waiting or not.
Declaration
function ReadEvent () : Event;
function PollEvent () : Any; // an Event, or nil
Remarks
ReadEvent waits; PollEvent answers nil at once when nothing has happened, which is what a loop with work of its own needs.
⚠️ One queue, keys and mouse together, so a click and a keystroke keep the order they happened in. That is the whole reason Turbo Vision had one queue rather than two.
⚠️ ReadKey is unchanged. It answers keys alone and discards mouse events it passes over, so a program written before the mouse existed means exactly what it did. KeyPressed likewise does not report a queued click as a key.
The mouse is off until EnableMouse asks for it, so until then these answer only keys.
ReadEvent presents while it waits in graph, as ReadKey does, so a program waiting on the mouse still blinks. In crt, a screen that is not a terminal can receive nothing, so ReadEvent answers a KeyClose event at once and PollEvent answers nil.
Raises Graph is not open. or Crt is not open.
See also
EnableMouse, Event, EventKinds, ReadKey
Example
uses graph;
InitGraph (1280, 800, 'events', False);
EnableMouse ();
var Panel := ViewPort (200, 100, 400, 300, 1);
// Nothing has happened, and PollEvent never waits.
System.WriteLn ('nothing yet: ', PollEvent () = nil);
// A key, queued as an event like any other.
EnqueueKey ('a');
var E := ReadEvent ();
System.WriteLn ('kind is key: ', E.Kind = EventKey);
System.WriteLn ('the key: ', E.Key);
// ReadKey still answers keys alone, so a program written before the mouse
// existed means exactly what it did.
EnqueueKey ('b');
System.WriteLn ('ReadKey: ', ReadKey ());
CloseGraph ();
Shell
nothing yet: true
kind is key: true
the key: a
ReadKey: b
ReadKey
function — unit graph and crt
Function
Returns the next key, waiting for one if none is ready.
Declaration
function ReadKey () : Char;
Remarks
⚠️ In crt, a screen that is not a terminal can never receive a key, so ReadKey answers KeyClose at once rather than waiting for something that cannot come, and KeyPressed is always False. See IsTerminal.
One Char per key, always:
| the key | the answer |
|---|---|
| a typed character | itself, layout and shift applied — Unicode included, é and 你 are single answers |
| an arrow, function or navigation key | its constant — KeyUp, KeyF1, … |
| Enter, Escape, Tab, Backspace | #13 #27 #9 #8 |
| a Ctrl letter | its low character — Ctrl-A is #1 |
| the window's close button | KeyClose |
Nothing echoes, as Turbo Pascal had it. What is not kept is TP's extended-key protocol — #0 and then a scan code on the next call — which was the BIOS showing through, two reads per arrow.
While waiting, the blink phase keeps beating: the wait presents once a frame, so ReadKey is also the idle a finished screen wants, and the demos end with exactly that.
Raises Graph is not open. without a window.
See also
Example
The idiom is a loop, and it needs a keyboard:
while ReadKey () <> #27 do
Write ('.');
examples/keys.a24 is that loop grown up — every key echoed by name until Esc. What can run unattended is the empty-queue side:
uses graph;
InitGraph (640, 480, 'keys', False);
System.WriteLn (KeyPressed ());
CloseGraph ();
System.WriteLn ('no key was waiting');
Shell
false
no key was waiting
ReadLines
function and procedure — unit file
Function
Reads and writes a text file as a list of lines.
Declaration
function ReadLines (Path : String) : List;
procedure WriteLines (Path : String, Lines : List);
Remarks
The lines come back without their newlines, and the two are inverses: WriteLines gives every line a newline including the last, which is what makes a file read back unchanged.
⚠️ A trailing newline does not make an empty last line. A file of three lines answers three however it ends, which is what almost every program wants and what a naive split on newline gets wrong.
⚠️ Either newline convention reads the same. A carriage return immediately before a newline belongs to the newline and is dropped, so a file written on Windows reads as it would here. A carriage return anywhere else is just a character.
An empty list writes an empty file, and an empty file reads back as no lines.
Raises ReadAll's messages.
See also
Example
uses file;
// WriteLines and ReadLines are inverses: each line gets a newline, including
// the last, which is what makes the file read back unchanged.
WriteLines ('poem.txt', ['the sea', 'the sea', 'the open sea']);
var Back := ReadLines ('poem.txt');
System.WriteLn ('lines back: ', Back.Length);
System.WriteLn ('unchanged: ', Back[0] = 'the sea', ' ', Back[2] = 'the open sea');
// However the file ends, three lines are three lines.
WriteAll ('poem.txt', 'a' + #10 + 'b' + #10 + 'c');
System.WriteLn ('no trailing newline: ', ReadLines ('poem.txt').Length, ' lines');
WriteAll ('poem.txt', 'a' + #10 + 'b' + #10 + 'c' + #10);
System.WriteLn ('with one: ', ReadLines ('poem.txt').Length, ' lines');
// A file written on Windows reads the same as one written here: the carriage
// return goes with the newline, so the first line is one character and not two.
WriteAll ('poem.txt', 'a' + #13 + #10 + 'b' + #13 + #10);
System.WriteLn ('carriage returns: ', Length (ReadLines ('poem.txt')[0]), ' char');
Erase ('poem.txt');
Shell
lines back: 3
unchanged: true true
no trailing newline: 3 lines
with one: 3 lines
carriage returns: 1 char
RecordFile
class — unit file
Function
A file of fixed-size records, indexed by record rather than by byte.
Declaration
constructor RecordFile (Path : String, Width : Integer);
function Count () : Integer whole records held
function Read (N : Integer) : Any record N, as a new Buffer
function Read (N : Integer, Into : Any) : Integer
procedure Write (N : Integer, From : Any) replaces record N
procedure Append (From : Any) adds one at the end
procedure Flush () push what is buffered
procedure Close () flushed, released, idempotent
Remarks
Turbo Pascal's file of Record, as close as this language can come to it.
⚠️ The record type cannot carry over, and that is the whole of the difference. Pascal's Seek (F, 5) worked because the compiler knew sizeof(Customer); there is no sizeof here, and a class instance is a reference with no defined byte layout. So the width is given at construction and the field layout is the caller's — a Buffer is the record, with PutInt, PutDouble and byte indexing laying the fields out. That is less of a concession than it sounds: Pascal's string[30] was already a fixed-width field a programmer chose.
What does carry over is the useful half — random access by index, a file larger than memory, and updating one record in place, which a whole-file read and write cannot do without rewriting everything.
Count answers records, as Pascal's FileSize did for a typed file. A trailing part-record is not counted.
The two Read forms differ only in allocation. Read (N) answers a Buffer of its own and reads better; Read (N, Into) fills one the caller owns and allocates nothing, which is what a walk over many thousands of records wants. Into must hold at least a record; a larger one is filled from its start and the rest left alone.
Write at an index equal to Count () appends, which is what Append does more plainly. Anything past that is refused rather than leaving a hole.
The file is opened for reading and writing without being emptied, and is created if absent — so a record file is opened the same way whether or not it exists yet.
Raises RecordFile: a record must have a positive size., RecordFile: cannot open '<Path>'., Read: there is no record <N>. and its Write counterpart, <Member>: needs a buffer., <Member>: the buffer is smaller than a record., and <Member>: the file is closed. once closed.
See also
Example
uses file;
const Width := 16; // an Integer at 0, a Double at 8
var F := RecordFile ('stock.dat', Width);
for var I := 0; I < 3; I := I + 1 do
begin
var R := Buffer (Width);
R.PutInt (0, 100 + I);
R.PutDouble (8, 1.5 * I);
F.Append (R);
end
WriteLn ('records: ', F.Count ());
// One record changes; the others are not rewritten.
var Upd := Buffer (Width);
Upd.PutInt (0, 999);
Upd.PutDouble (8, 4.25);
F.Write (1, Upd);
// The allocation-free form, one buffer reused down the file.
var Into := Buffer (Width);
for var I := 0; I < F.Count (); I := I + 1 do
begin
F.Read (I, Into);
WriteLn (I, ': ', Into.GetInt (0), ' ', Str (Into.GetDouble (8), 2));
end
F.Close ();
WriteLn ('bytes: ', FileSize ('stock.dat'));
Erase ('stock.dat');
Shell
records: 3
0: 100 0.00
1: 999 4.25
2: 102 3.00
bytes: 48
Rectangle
procedure, alias of ViewPort.Rectangle — unit graph
Function
Draws a rectangle's outline on a viewport.
Declaration
procedure Rectangle (V : ViewPort, X1 : Integer, Y1 : Integer, X2 : Integer, Y2 : Integer);
Remarks
An alias of the method: Rectangle (V, …) is V.Rectangle (…).
Four Line calls in the current style and thickness.
⚠️ The pen is put back where it was, not left at the figure's corner: a figure is not a journey, and Arc, Circle, Bar and Bar3D keep the same rule. Only Line, LineTo and LineRel move the pen, because moving it is what they are for.
The outline only; there is no filled form yet.
Raises CloseGraph has closed this surface. once the window it belongs to has gone.
See also
Bar, Bar3D, Line, SetLineStyle
Example
See Line, which frames its chart with one.
Repeat
extension function — unit strings
Function
Returns its argument written the given number of times, end to end.
Declaration
extension function Repeat (S : String, Times : Integer) : String;
Remarks
A one-character literal is a Char rather than a String, and a Char is accepted where a String is declared — Repeat ('-', 40) is the call the routine exists for, and Repeat ('ab', 3) works the same way. (The two are distinct types but compare equal from 0.3.0 onward, so nothing here needs Str ('-').)
A Times of zero answers the empty string, which is what makes the routine usable for a width that may come to nothing. A negative Times raises rather than answering empty, there being no reading of it that was intended.
Both spellings work: Repeat (S, 3) and S.Repeat (3).
Raises Repeat needs a count of zero or more. for a negative count.
See also
Example
uses strings;
WriteLn (Repeat ('-', 20));
WriteLn ('ab'.Repeat (3));
WriteLn ('[' + Repeat ('x', 0) + ']');
Shell
--------------------
ababab
[]
Replace
extension function — unit strings
Function
Returns its argument with every occurrence of one string changed to another.
Declaration
extension function Replace (S : String, What : String, With : String) : String;
Remarks
Every occurrence rather than the first, which is the commoner need and the one the core cannot answer in a line. Replacing only the first is Pos followed by Delete and Insert.
The scan never re-reads what it has just written, so a replacement containing the thing it replaces terminates rather than running forever: Replace ('aa', 'a', 'aa') answers aaaa.
An empty With is legitimate and removes every occurrence. An empty What raises, for the same reason Split's does — there is no sequence of replacements that would mean it.
Both spellings work: Replace (S, ',', '-') and S.Replace (',', '-').
Raises Replace needs something to look for. for an empty What.
See also
Example
uses strings;
WriteLn ('a,b,c'.Replace (',', ' and '));
// Every occurrence, and an empty replacement removes them all.
WriteLn ('1,000,000'.Replace (',', ''));
// The replacement is never rescanned, so a pattern inside it terminates.
WriteLn ('aa'.Replace ('a', 'aa'));
Shell
a and b and c
1000000
aaaa
Round
function — unit math
Function
Returns its argument rounded to the nearest Integer.
Declaration
function Round (X : Double) : Integer;
Remarks
⚠️ A tie rounds to the EVEN neighbor, not away from zero. Round (2.5) is 2 and Round (3.5) is 4; Round (0.5) is 0 and Round (-2.5) is -2. This is not the schoolbook rule, which would answer 3 for 2.5, and the difference shows on exactly the values a test is most likely to try.
Two reasons for it. Consistency downward: ties-to-even is what IEEE 754 already does for every arithmetic result in the language, so a Round breaking ties the other way would be the one operation disagreeing with the arithmetic beneath it. Bias: rounding half away from zero sends every tie away from the center and so pushes a column of figures upward on average, where ties-to-even sends half each way and does not drift.
Away from a tie there is no subtlety — Round (2.4) is 2 and Round (2.6) is 3.
The result is an Integer proper, so it may be added to one or passed to Odd. An Integer argument is accepted and answers itself.
Every finite Double is answered exactly, on the same two paths as Trunc: above 2^63 there is no nearest integer to search for, the value being one already. Only NaN and the infinities are refused, raising Round of NaN. and Round of an infinity..
The primitive is libm's llrint, which rounds by the current floating-point rounding direction. Nothing in the library changes that direction, and its default is to-nearest-with-ties-to-even — the rule above.
See also
Example
uses math;
WriteLn (Round (2.4));
WriteLn (Round (2.6));
for var V in [0.5, 1.5, 2.5, 3.5] do
WriteLn (Str (V) + ' rounds to ' + Str (Round (V)));
Shell
2
3
0.5 rounds to 0
1.5 rounds to 2
2.5 rounds to 2
3.5 rounds to 4
SameContent
extension function — unit reflect
Function
Returns whether two values hold the same content, field by field and element by element.
Declaration
extension function SameContent (A : Any, B : Any) : Boolean;
Remarks
This is the comparison = does not make. Instances, Lists and Maps compare by identity, so two separately built values holding the same things are unequal under = and equal here. The two spellings are deliberately different words: = keeps its meaning, and nothing about this routine changes what an existing comparison answers.
An instance is compared against the field list its class declares, so adding a field cannot leave the comparison quietly behind — which is what a hand-written walk per class could not promise. A private field is read, for the same reason Describe renders one.
Types must match before content is examined, so the Integer 5 and the Double 5.0 are not the same content, and neither are two instances of different classes. Widening is an assignment rule rather than an equality one.
An ordered collection — a List, a Stack or an Array — is compared by position. A Map is compared by key and value and not by insertion order, two maps holding the same pairs being the same map. A Set is compared by membership, two sets holding the same values being the same set; its members are matched with the language's own equality, so a set of instances compares those by identity, which is the one place this routine stops short of content. A Buffer is compared byte by byte.
Terminates on a cyclic graph. Arriving at a container already entered answers True rather than descending again, which is the only answer that terminates: two cycles of the same shape are the same content, and the walk has already committed to every field that could distinguish them.
Both spellings work: SameContent (A, B) and A.SameContent (B).
Never raises. Any two values have an answer.
See also
Example
uses reflect;
class Point;
var
X : Integer;
Y : Integer;
begin
constructor Init (AX : Integer, AY : Integer);
begin
X := AX;
Y := AY;
end
end
var A := Point (1, 2);
var B := Point (1, 2);
WriteLn (A = B);
WriteLn (A.SameContent (B));
WriteLn (SameContent ([1, 2], [1, 2]));
WriteLn ([1, 2] = [1, 2]);
WriteLn (SameContent (5, 5.0));
Shell
false
true
true
false
false
ScreenHeight
function — unit graph
Function
Returns the desktop's height in pixels.
Declaration
function ScreenHeight () : Integer;
Remarks
Everything said of ScreenWidth holds here, for rows. Note that on macOS a fullscreen window's height can be slightly less than this, because the menu bar stays — GetMaxY is the truth about the window, this is the truth about the desktop.
See also
GetMaxY, InitGraph, ScreenWidth
Example
See ScreenWidth, which shows both.
ScreenWidth
function — unit graph
Function
Returns the desktop's width in pixels.
Declaration
function ScreenWidth () : Integer;
Remarks
Usable before InitGraph, which is its purpose: it answers how much room the desktop has, so a program can choose a window size to fit. It is unchanged by windows opening and closing.
This and GetMaxX answer different questions — how big a window could be, versus how big this one is — and keeping the names apart is what lets the GetMaxX drawing idiom stay safe in a window smaller than the screen.
See also
GetMaxX, InitGraph, ScreenHeight
Example
uses graph;
// The desktop's size is the machine's, so only its soundness can be shown.
System.WriteLn (ScreenWidth () > 0);
System.WriteLn (ScreenHeight () > 0);
System.WriteLn (ScreenWidth () >= 640);
Shell
true
true
true
Sector
procedure, alias of ViewPort.Sector — unit graph
Function
Fills and outlines an elliptical sector on a viewport.
Declaration
procedure Sector (V : ViewPort, X : Integer, Y : Integer, StartAngle : Integer,
EndAngle : Integer, XRadius : Integer, YRadius : Integer);
Remarks
An alias of the method: Sector (V, …) is V.Sector (…).
PieSlice with two radii, exactly as Ellipse is Circle with two — filled with the current fill pattern and color, then outlined with the pen: the elliptical arc, and the two radii closing it to the center.
With equal radii it is PieSlice: there is a test asserting the two paint the same pixels. They share one primitive underneath, so they cannot drift into filling different shapes.
Angles are the parametric ones Ellipse uses, so a sector of a wide ellipse spans the same fraction of the figure that the same angles span of a circle — which is what makes a pie chart drawn in perspective come out with its shares intact. A sweep of 360 is the whole ellipse and draws no radii, the two coinciding.
The fill and the outline are separate pens, and the pen is not moved.
Raises Sector needs radii of zero or more. and CloseGraph has closed this surface.
See also
Ellipse, FillEllipse, GetArcCoords, PieSlice, SetFillStyle
Example
uses graph;
InitGraph (640, 480, 'sector', False);
var V := ViewPort (40, 60, 520, 320, 1);
// A pie chart drawn in perspective: the same shares as a round one, laid on
// an ellipse, which is what a sector is for.
var Shares := [30, 25, 20, 15, 10];
var Inks := [LightRed, Yellow, LightCyan, LightGreen, LightMagenta];
var At := 0;
SetColor (V, White);
for var I := 0; I < 5; I := I + 1 do
begin
SetFillStyle (V, SolidFill, Inks[I]);
Sector (V, 250, 160, At * 36 div 10, (At + Shares[I]) * 36 div 10, 200, 90);
At := At + Shares[I];
end
Show (V);
// Wide across, shallow down: the rim is 200 out but only 90 up, so a point
// 100 above the center is outside it and one 80 above is not.
System.WriteLn (V.Buf.GetInt ((159 * 480 + 429) * 4) <> 0);
System.WriteLn (V.Buf.GetInt ((79 * 480 + 249) * 4) <> 0);
System.WriteLn (V.Buf.GetInt ((59 * 480 + 249) * 4) <> 0);
CloseGraph ();
Shell
true
true
false
SetAspectRatio
procedure — unit graph
Function
Imposes an aspect ratio in place of the one measured from the window.
Declaration
procedure SetAspectRatio (Ratio : Double);
Remarks
GetAspectRatio answers this instead of the measurement once it is set.
Turbo Pascal's existed because the value the BIOS reported was not always the value that made a circle look round on the monitor in front of you. The measurement here is exact — the logical space and the window are both known — so this is for wanting a different answer rather than for correcting a wrong one: drawing to square pixels deliberately, or matching a figure to a screenshot from elsewhere.
⚠️ Keep the measured value before overriding it. That is the way back; there is no verb to un-impose a ratio, because SetAspectRatio (Measured) already is one.
It is screen-wide, as GetAspectRatio is: the stretch belongs to the window and no single surface owns it. CloseGraph clears it, so a new window starts from its own measurement.
A single Double, where Turbo Pascal took two Words with the vertical one pegged at 10000.
Raises SetAspectRatio wants a ratio above zero., and Graph is not open. without a window.
See also
Circle, Ellipse, GetAspectRatio
Example
uses graph;
InitGraph (640, 480, 'aspect', False);
// Keep the measured one first: that is the way back, there being no verb
// to un-impose a ratio.
var Measured := GetAspectRatio ();
System.WriteLn ('measured ', Measured);
// Draw to square pixels deliberately, ignoring the window's stretch.
SetAspectRatio (1.0);
System.WriteLn ('imposed ', GetAspectRatio ());
SetAspectRatio (Measured);
System.WriteLn ('restored ', GetAspectRatio () = Measured);
CloseGraph ();
Shell
measured 0.8333333333333334
imposed 1.0
restored true
SetBkColor
procedures, aliases of ViewPort.SetBkColor and GetBkColor — unit graph
Function
Sets the color Clear returns a viewport to.
Declaration
procedure SetBkColor (V : ViewPort, Color : Integer);
function GetBkColor (V : ViewPort) : Integer;
Remarks
Aliases of the methods: SetBkColor (V, …) is V.SetBkColor (…).
⚠️ Transparent by default, which is what a fresh viewport already is and what lets whatever lies beneath show through when it is cleared. Give it a color and Clear paints that instead. This is a viewport's answer to a window's TextBackground, which has always governed what ClrScr fills.
Turbo Pascal's SetBkColor set the whole screen's background — there was one screen and no stack to see through. It is per surface here for the same reason everything else is.
⚠️ Nothing else consults it. In particular EmptyFill still paints nothing at all rather than painting this: leaving pixels alone is what empty has to mean on a stack of surfaces, and painting them would hide what is under them. See FillStyles.
It is a third pen, independent of SetColor's and SetFillStyle's; setting one never disturbs another.
Raises SetBkColor wants a color or Transparent. below Transparent or above White — Blink is ink's alone, so White + Blink is refused — and CloseGraph has closed this surface. once the window has gone.
See also
Clear, ClearViewPort, Colors, SetFillStyle, TextBackground
Example
uses graph;
InitGraph (640, 480, 'bk', False);
var Under := ViewPort (50, 50, 200, 100, 1);
var Over := ViewPort (50, 50, 200, 100, 2);
SetFillStyle (Under, SolidFill, Red);
Bar (Under, 1, 1, 200, 100);
// Transparent by default, so clearing the upper viewport lets the lower one
// show through it again.
SetFillStyle (Over, SolidFill, Yellow);
Bar (Over, 1, 1, 200, 100);
ClearViewPort (Over);
System.WriteLn ('transparent: ', GetPixel (Over, 20, 20) = Transparent);
// Given a background, clearing paints that instead.
SetBkColor (Over, Blue);
Bar (Over, 1, 1, 200, 100);
ClearViewPort (Over);
System.WriteLn ('blue: ', GetPixel (Over, 20, 20) = Blue);
System.WriteLn ('reported: ', GetBkColor (Over) = Blue);
CloseGraph ();
Shell
transparent: true
blue: true
reported: true
SetBlinkRate
procedure — unit graph
Function
Sets how long each blink phase lasts, in milliseconds.
Declaration
procedure SetBlinkRate (Ms : Integer);
Remarks
Blinking ink is visible for Ms milliseconds and hidden for the same, so a full blink takes twice this. Two cadences with history behind them:
267 | the adapter's own — sixteen frames of sixty each way; the default |
533 | the slower, one-second blink of the console caret that came after |
The rate is a program-level setting: TextMode and NormVideo reset the colors and the blink flag, never this. A fresh InitGraph restores 267.
Turbo Pascal offered no such method, because the rate lived in a video register — the hardware's limitation, not a design worth inheriting.
Raises SetBlinkRate needs a positive time. for an Ms of zero or less.
See also
Example
uses graph;
InitGraph (640, 480, 'cadence', False);
SetBlinkRate (533);
TextColor (Yellow + Blink);
Write ('the unhurried blink');
CloseGraph ();
System.WriteLn ('set');
Shell
set
SetColor
procedure, alias of ViewPort.SetColor — unit graph
Function
Sets the color a viewport's pen draws in.
Declaration
procedure SetColor (V : ViewPort, Color : Integer);
Remarks
An alias of the method: SetColor (V, …) is V.SetColor (…).
Turbo Pascal's SetColor, and it governs everything the surface draws — the Line family and the OutText pair alike. One pen for lines and letters both. A fresh viewport draws in White.
PutPixel is the exception: it names its own color and ignores the pen.
Raises SetColor wants an RGB color. for a negative — there being no transparent ink — and for anything above White. ⚠️ The ceiling is checked here so it cannot surface later. Without it an impossible color reached the pixel writer and came back as Integer … is too large to use here. from Buffer.PutInt, mid-draw, naming neither the color nor the call that set it.
⚠️ Blink is not a pen color. It belongs to TextColor, the only member that reads it, so White + Blink is refused here. The same ceiling applies to SetBkColor, SetFillStyle, PutPixel and TextBackground.
Raises CloseGraph has closed this surface. once the window has gone.
See also
Colors, GetColor, Line, SetLineStyle
Example
uses graph;
InitGraph (640, 480, 'color', False);
var V := ViewPort (10, 10, 100, 60, 1);
SetColor (V, LightCyan);
Line (V, 1, 1, 99, 59);
OutTextXY (V, 4, 4, 'the same pen');
Show (V);
System.WriteLn (GetColor (V) = LightCyan);
CloseGraph ();
Shell
true
SetFillStyle
procedures, aliases of ViewPort.SetFillStyle and SetFillPattern — unit graph
Function
Sets the pattern and color figures are filled with.
Declaration
procedure SetFillStyle (V : ViewPort, Style : Integer, Color : Integer);
procedure SetFillPattern (V : ViewPort, Rows : List, Color : Integer);
function GetFillStyle (V : ViewPort) : Integer;
function GetFillColor (V : ViewPort) : Integer;
Remarks
Aliases of the methods: SetFillStyle (V, …) is V.SetFillStyle (…).
⚠️ The fill is a separate pen from the one SetColor sets. A figure may be outlined in one color and filled in another, which is how Turbo Pascal's Bar3D and PieSlice were drawn. Setting one never disturbs the other.
Style is one of the fill patterns — an eight-by-eight bit pattern tiled across whatever is being filled. SetFillPattern supplies eight rows of the caller's own instead, each the eight bits of one row with the high bit leftmost, and sets the style to UserFill:
SetFillPattern (V, [255, 129, 129, 129, 129, 129, 129, 255], Yellow); // a box
⚠️ The pattern is tiled from the surface's origin, not the figure's. Two figures side by side therefore share one weave rather than each starting its own, which is what makes a patterned fill look woven rather than tiled.
A fresh viewport fills SolidFill in White, as it draws.
Nothing consults this state yet — the figures that take a fill are still to come. It is settled first because they will all want it, and because the choice between one pen and two is theirs to inherit rather than to argue.
Raises SetFillStyle wants an RGB color. for a color below zero or above White, and SetFillStyle wants a known pattern., SetFillStyle wants UserFill from SetFillPattern. for UserFill itself, SetFillStyle wants an RGB color., SetFillPattern wants eight rows., and SetFillPattern wants an RGB color.
See also
Colors, FillStyles, GetFillPattern, GetFillSettings, SetColor, SetLineStyle
Example
uses graph;
InitGraph (640, 480, 'fill', False);
var V := ViewPort (10, 10, 100, 100, 1);
SetFillStyle (V, HatchFill, LightGreen);
System.WriteLn (GetFillStyle (V) = HatchFill);
System.WriteLn (GetFillColor (V) = LightGreen);
// The fill pen and the drawing pen are separate.
SetColor (V, Red);
System.WriteLn (GetColor (V) = Red);
System.WriteLn (GetFillColor (V) = LightGreen);
// A pattern of one's own: a hollow box, eight by eight.
SetFillPattern (V, [255, 129, 129, 129, 129, 129, 129, 255], Yellow);
System.WriteLn (GetFillStyle (V) = UserFill);
CloseGraph ();
Shell
true
true
true
true
true
SetLineStyle
procedure, alias of ViewPort.SetLineStyle — unit graph
Function
Sets the pattern and thickness a viewport draws lines with.
Declaration
procedure SetLineStyle (V : ViewPort, Style : Integer, Pattern : Integer, Thickness : Integer);
Remarks
An alias of the method: SetLineStyle (V, …) is V.SetLineStyle (…).
Style is one of the line styles. The style's sixteen bits are walked along the line, one bit to the pixel and repeating, so a DottedLn hundred-pixel line paints fifty. Pattern is consulted only for UserBitLn; the other styles carry their own bits.
⚠️ Thickness spreads across the axis the line runs least along, which is what keeps a thick diagonal from breaking into a staircase of blobs. NormWidth is 1 and ThickWidth is 3, and any positive count is allowed — Turbo Pascal permitted only those two.
Raises SetLineStyle wants a known style., SetLineStyle needs a thickness of 1 or more., and CloseGraph has closed this surface.
See also
Example
See Line, which draws dashed and solid from one viewport.
SetPalette
procedures — unit graph and crt
Function
Rebinds what the sixteen color names mean on a surface.
Declaration
procedure SetPalette (Palette : Map); // the screen
procedure SetPalette (Surface, Palette : Map); // that Window or ViewPort
function GetPalette () : Map; // the screen
function GetPalette (Surface) : Map; // that Window or ViewPort
Remarks
crt has the same pair, and the same rule, on a Window or the screen.
A palette is a Map from one of the sixteen color names to the RGB it should mean here. It is per surface, as every pen is — a themed screen with an unthemed window over it is ordinary.
SetPalette (V, [LightGray : 12550144, White : 16768256]);
⚠️ A name the map does not list means itself. A partial palette is the ordinary case: a theme says only what it changes, and rebinding one color does not require restating the other fifteen.
⚠️ It governs what is drawn next, not what is already drawn. Setting a palette re-themes the pens in force — the drawing color, the fill, the background, the ink — so the pen you are holding follows the theme without being set again. But pixels and cells already laid keep the colors they were laid in. Re-theming a finished picture means drawing it again.
That is the half of Turbo Pascal's palette this cannot do, and the reason is structural: SetPalette there wrote a hardware register and the framebuffer held indices, so one write recolored everything already on screen. A surface here holds final colors. See DESIGN.md.
The rule
⚠️ A color equal to one of the sixteen is a name; anything else is a literal. The constants are their RGB values — Red is 11141120 — so at run time the lookup sees a number and cannot tell which was written:
SetColor (V, 11141120) == SetColor (V, Red)
Turbo Pascal had no such ambiguity because there Red was 4 — an index, a space of its own. Making the constants the CGA RGB values is worth more than the collision costs: it is what lets any RGB be passed wherever a color is wanted, with the sixteen as a vocabulary rather than a limit.
Three things hold it down, and none needs any care from the caller:
- Inert until asked for. No palette, no lookup, and every name means itself.
- Unlisted means itself, so a theme rebinding three names puts only those three at risk.
- ⚠️
PutPixelandPutImagebypass the pens entirely and are never themed. That is the way to lay an exact color under a palette.
Worth knowing when choosing what to rebind: Black and White are the two of the sixteen that arithmetic actually produces — the end of a fade, the top of a ramp — where the other fourteen rarely arise by accident.
What the getters answer
GetColor, GetFillColor, GetBkColor and GetFillSettings answer the name they were given, not what the palette made of it, so save-and-restore round-trips instead of theming twice. GetPixel answers what is actually on the surface, which is the themed color. The two are different questions and both are worth asking.
HighVideo and LowVideo brighten the name and then theme it afresh, so Blue becomes LightBlue and the palette says what that means. Blink is bit 24 added to an ink rather than a color of its own, so it is set aside for the lookup and put back. GraphDefaults keeps the palette — it is what the names mean here, not itself a pen.
GetPalette answers a copy, as GetFillPattern does, and what is handed to SetPalette is copied too.
The surface-first forms take an untyped surface and ask what it is, as MoveTo does: both kinds take a palette, so two declarations of one arity would put the choice on the argument's type.
Raises SetPalette wants one of the sixteen color names as a key., SetPalette wants RGB colors., SetPalette wants a Window or a ViewPort., Graph is not open., and CloseGraph has closed this surface.
See also
Colors, GetColor, PutPixel, SetBkColor, TextColor
Example
uses graph;
InitGraph (640, 480, 'palette', False);
var V := ViewPort (50, 50, 300, 200, 1);
// An amber terminal, in three entries. The thirteen names not listed go on
// meaning themselves, so a theme says only what it changes.
var Amber := [LightGray : 12550144, White : 16768256, DarkGray : 5583872];
SetPalette (V, Amber);
SetColor (V, LightGray);
Line (V, 10, 10, 200, 10);
SetColor (V, LightCyan);
Line (V, 10, 20, 200, 20);
System.WriteLn ('themed: ', GetPixel (V, 50, 10) = 12550144);
System.WriteLn ('untouched:', GetPixel (V, 50, 20) = LightCyan);
// The getter answers the name it was given, not what the theme made of it,
// so a saved color goes back without being themed twice.
System.WriteLn ('asked for ', GetColor (V) = LightCyan);
// PutPixel bypasses the pens entirely and so is never themed: it is the way
// to lay an exact color under a palette.
PutPixel (V, 5, 5, LightGray);
System.WriteLn ('exact: ', GetPixel (V, 5, 5) = LightGray);
// A palette governs what is drawn NEXT, not what is already drawn. The pen
// is holding LightGray again here, so the new theme reaches it without it
// being set a second time.
SetColor (V, LightGray);
SetPalette (V, [LightGray : Red]);
System.WriteLn ('already drawn stays ', GetPixel (V, 50, 10) = 12550144);
Line (V, 10, 30, 200, 30);
System.WriteLn ('the pen followed ', GetPixel (V, 50, 30) = Red);
CloseGraph ();
Shell
themed: true
untouched:true
asked for true
exact: true
already drawn stays true
the pen followed true
SetSeed
procedure — unit random
Function
Seeds the generator so that the sequence following is repeatable.
Declaration
procedure SetSeed (Seed : Integer);
Remarks
The same seed always yields the same sequence. This is what makes a program using random testable, and every test in the unit begins with it.
⚠️ Every bit of Seed contributes, which took work. srand48 beneath keeps only the low 32 bits of its argument — measured, not assumed: raw srand48 gives seeds 42, 42 + 2³² and 42 + 2³³ the same stream. An Algol-24 Integer is unbounded, so passing one straight through would silently collide distinct seeds. The C wrapper folds the high half onto the low half first.
A negative seed is accepted and behaves like any other.
See also
Example
uses random;
SetSeed (99);
WriteLn (RandomInteger (1000));
WriteLn (RandomInteger (1000));
SetSeed (99);
WriteLn (RandomInteger (1000));
Shell
380
504
380
SetTextJustify
procedure, alias of ViewPort.SetTextJustify — unit graph
Function
Sets where free text sits relative to the point it is placed at.
Declaration
procedure SetTextJustify (V : ViewPort, Horiz : Integer, Vert : Integer);
Remarks
An alias of the method: SetTextJustify (V, …) is V.SetTextJustify (…).
Horiz is LeftText, CenterText or RightText and says which end of the text meets the point; Vert is TopText, CenterText or BottomText and says which edge of the line does. A fresh viewport is LeftText, TopText — Turbo Pascal's default, and the top-left corner OutTextXY has always placed.
This is what TextWidth and TextHeight are for, applied by the unit instead of by the caller. Centering a label becomes one call and one placement rather than a measurement and a subtraction:
SetTextJustify (V, CenterText, CenterText);
OutTextXY (V, 150, 50, 'centered');
⚠️ Justification is measured along the text's own run and across it, not along the screen's axes. Under SetTextStyle a turned string justifies about its own start, middle and end — so RightText on text running downward puts the end of the run at the point. Upright, which is the ordinary case, the two readings are the same.
It governs OutText as well, which is Turbo Pascal's rule. Chaining OutText calls only reads sensibly under LeftText, the advance being the width of what was drawn either way.
Raises SetTextJustify wants a known justification., and CloseGraph has closed this surface. once the window has gone.
See also
OutText, OutTextXY, SetTextStyle, TextJustify, TextWidth
Example
uses graph;
InitGraph (640, 480, 'justify', False);
var V := ViewPort (50, 50, 300, 100, 1);
SetColor (V, White);
// Centered about the middle of the viewport both ways, in one call. This is
// what TextWidth and TextHeight are for, applied by the unit rather than by
// the caller.
SetTextJustify (V, CenterText, CenterText);
OutTextXY (V, 150, 50, 'centered');
Show (V);
var Left := 9999;
var Right := 0;
for var Y := 1; Y <= 100; Y := Y + 1 do
for var X := 1; X <= 300; X := X + 1 do
if GetPixel (V, X, Y) <> Transparent then
begin
if X < Left then Left := X;
if X > Right then Right := X;
end
System.WriteLn ('the label is ', TextWidth (V, 'centered'), ' wide');
System.WriteLn ('its ink runs ', Left, ' to ', Right);
System.WriteLn ('straddling ', (Left + Right) div 2);
CloseGraph ();
Shell
the label is 128 wide
its ink runs 88 to 211
straddling 149
SetTextStyle
method of ViewPort — unit graph
Function
Sets the direction and size free text on a viewport is drawn in.
Declaration
procedure SetTextStyle (V : ViewPort, Direction : Integer, CharSize : Integer);
Remarks
Direction is a quarter turn counterclockwise in degrees — 0, 90, 180 or 270, and anything else raises. A turn of 90° sends the glyph's top edge to the left, so the text reads bottom to top: a chart's Y-axis label, which is what the turn was wanted for.
CharSize magnifies the glyphs by a whole number, 1 being the font's own size. Magnification replicates pixels, so a doubled glyph covers four times the area and the antialiasing doubles with it — crisp rather than blurred, and unmistakably scaled rather than redrawn.
⚠️ The turned text is anchored at the same corner. A 90° turn puts a 16 × 32 glyph into a 32 × 16 box whose top-left is the OutTextXY position, so the text grows right and down from that point as it always does; only the letters lie on their side. The advance follows the turn — right, up, left or down — so successive OutText calls read in the direction set.
⚠️ Celled text has neither setting, and cannot. A rotated glyph does not fit a half-width cell, and a magnified one does not fit at all — which is why these live on the viewport and not beside TextColor. The style is the viewport's own; the grid never inherits it.
Turbo Pascal's SetTextStyle took a font as its first argument, selecting among .CHR stroked-font files. Here the glyph file installed by InstallUserFont is the font, so selecting one is installing one and the parameter has nothing left to choose.
Raises SetTextStyle wants 0, 90, 180 or 270 degrees. and SetTextStyle needs a CharSize of 1 or more.
See also
InstallUserFont, OutTextXY, ViewPort
Example
uses graph;
InitGraph (640, 480, 'style', False);
var Chart := ViewPort (1, 1, 400, 300, 1);
// A Y-axis label, reading bottom to top, at double size.
Chart.SetTextStyle (90, 2);
Chart.OutTextXY (20, 280, 'millivolts');
Chart.SetTextStyle (0, 1);
Chart.OutTextXY (60, 290, 'seconds');
Chart.Show ();
System.WriteLn (Chart.Dir);
System.WriteLn (Chart.Size);
CloseGraph ();
Shell
0
1
SetUserCharSize
procedure, alias of ViewPort.SetUserCharSize — unit graph
Function
Magnifies free text by a ratio rather than a whole number.
Declaration
procedure SetUserCharSize (V : ViewPort, MultX : Integer, DivX : Integer,
MultY : Integer, DivY : Integer);
Remarks
An alias of the method. MultX over DivX across, MultY over DivY down, so (3, 2, 1, 1) is half again as wide at the same height — which SetTextStyle's whole-number CharSize cannot express at all.
A whole-number size is the ratio N over one, so the two verbs are the same setting and either replaces what the other set.
⚠️ Turbo Pascal's worked only on its stroked fonts and was ignored by the bitmap one. The glyphs here are a bitmap and this works on them: the stamper walks the destination and samples back, so it can squeeze as readily as magnify. Squeezed far enough a glyph loses rows and columns, which is what sampling a bitmap costs and is the honest picture of it.
TextWidth and TextHeight follow the ratio, so justification and centering stay right at any size.
GetTextSettings reports the four terms, and reports CharSize as 0 while a ratio is in force.
Raises SetUserCharSize wants positive terms., and CloseGraph has closed this surface. once the window has gone.
See also
GetTextSettings, SetTextJustify, SetTextStyle, TextWidth
Example
uses graph;
InitGraph (640, 480, 'charsize', False);
var V := ViewPort (50, 50, 400, 150, 1);
System.WriteLn ('one to one ', TextWidth (V, 'Wide'), ' by ',
TextHeight (V, 'Wide'));
// Half again as wide at the same height, which a whole-number CharSize
// cannot express at all.
SetUserCharSize (V, 3, 2, 1, 1);
System.WriteLn ('three halves ', TextWidth (V, 'Wide'), ' by ',
TextHeight (V, 'Wide'));
// And squeezed, which Turbo Pascal's bitmap font could not do either.
SetUserCharSize (V, 1, 2, 1, 2);
System.WriteLn ('half ', TextWidth (V, 'Wide'), ' by ',
TextHeight (V, 'Wide'));
SetColor (V, White);
SetUserCharSize (V, 4, 1, 2, 1);
OutTextXY (V, 10, 10, 'Wide');
Show (V);
// A CharSize of zero says the size is a ratio; the four terms say which.
var T := GetTextSettings (V);
System.WriteLn ('reported ', T.CharSize, ' ratio ', T.MultX, '/',
T.DivX, ' by ', T.MultY, '/', T.DivY);
CloseGraph ();
Shell
one to one 64 by 32
three halves 96 by 32
half 32 by 16
reported 0 ratio 4/1 by 2/1
SetWriteMode
procedures, aliases of ViewPort.SetWriteMode and GetWriteMode — unit graph
Function
Sets how pen strokes combine with what is already on the surface.
Declaration
procedure SetWriteMode (V : ViewPort, Mode : Integer);
function GetWriteMode (V : ViewPort) : Integer;
Remarks
Aliases of the methods. Mode is CopyPut or XorPut — the pen takes those two, where PutImage takes all six.
CopyPut lays the pen's color over whatever was there, which is how a fresh viewport draws. XorPut combines instead, so drawing the same figure twice puts the surface back exactly — a rubber-band line, a crosshair, a shape dragged over a picture that has to survive. Nothing needs saving first, which is what makes it worth having beside GetImage.
⚠️ It governs every stroke the pen makes: Line, LineTo, LineRel, Rectangle, DrawPoly, Arc, Circle and Ellipse. Turbo Pascal named only the straight ones, which was an arbitrary line to draw through a set of verbs that all use one pen.
It does not govern the fills, which lay their own pen in runs, nor PutPixel, which writes a color of its own and bypasses the pen already.
Raises SetWriteMode wants CopyPut or XorPut., and CloseGraph has closed this surface. once the window has gone.
See also
GetImage, Line, PutModes, SetColor
Example
uses graph;
InitGraph (640, 480, 'writemode', False);
var V := ViewPort (50, 50, 200, 120, 1);
SetFillStyle (V, HatchFill, LightGreen);
Bar (V, 1, 1, 200, 120);
// The midpoint of the line below, so the check lands on ink.
var Was := GetPixel (V, 100, 60);
SetWriteMode (V, XorPut);
SetColor (V, Red);
// A rubber band: draw it to show it, draw it again to take it away, and what
// was underneath is back exactly. Nothing had to be saved.
Line (V, 10, 10, 190, 110);
System.WriteLn ('drawn: ', GetPixel (V, 100, 60) <> Was);
Line (V, 10, 10, 190, 110);
System.WriteLn ('undrawn: ', GetPixel (V, 100, 60) = Was);
// It governs the curves too, where Turbo Pascal named only the straight ones.
Circle (V, 100, 60, 40);
Circle (V, 100, 60, 40);
System.WriteLn ('circle: ', GetPixel (V, 100, 20) = GetPixel (V, 100, 100));
CloseGraph ();
Shell
drawn: true
undrawn: true
circle: true
Show
procedure, alias of ViewPort.Show — unit graph and crt
Function
Pushes a viewport's pixels to the screen.
Declaration
procedure Show (V : ViewPort);
Remarks
In crt this composites the surfaces and paints the cells that changed; nothing reaches the terminal when standard output is not one.
An alias of the method: Show (V) is V.Show ().
Drawing writes into the viewport's own buffer and is not visible until something presents the stack; this is that. So is any text verb, and so is ReadKey while it waits — a program that ends on ReadKey need not call Show at all.
Raises CloseGraph has closed this surface. once the window it belongs to has gone.
See also
Example
See PutPixel and Line, which both end with one.
Sin
function — unit math
Function
Returns the sine of an angle given in radians.
Declaration
function Sin (X : Double) : Double;
Remarks
X is in radians. Multiply a degree measure by Pi / 180.
Sin (Pi / 2) answers exactly 1.0, which is the fortunate case; see Cos for the one that is not.
A foreign declaration onto libm's sin.
See also
Example
uses math;
WriteLn (Sin (0.0));
WriteLn (Sin (Pi / 2));
Shell
0.0
1.0
Sound
procedures — unit sound
Function
Starts and stops a tone.
Declaration
uses sound;
uses crt; // for Delay -- sound has none, to keep a bare one unambiguous
// Turbo Pascal's pair: a square wave on until told otherwise, and Delay is
// what gives a note its length. This is the case that wants crt's Delay; a
// tune played with Play needs no such thing, timing itself.
Sound (440);
Delay (120);
Sound (554);
Delay (120);
Sound (659);
Delay (120);
NoSound ();
// BASIC's PLAY, which Turbo Pascal never had. Score answers what it would
// sound without sounding it, so a tune can be checked.
var Tune := Score ('T120 O4 L8 CDEFGAB O5 C2');
System.WriteLn ('notes: ', Tune.Length);
System.WriteLn ('first: ', Tune[0][0], ' Hz');
System.WriteLn ('last: ', Tune[7][0], ' Hz');
System.WriteLn ('an eighth at 120 lasts ', Tune[0][1] + Tune[0][2], ' ms');
Play ('T160 O4 L8 CDEFGAB O5 C4');
System.WriteLn ('audible: ', SoundAvailable ());
CloseSound ();
Shell
notes: 8
first: 262 Hz
last: 523 Hz
an eighth at 120 lasts 250 ms
audible: false
SoundAvailable
function — unit sound
Function
Whether a real sound device could be opened.
Declaration
function SoundAvailable () : Boolean;
Remarks
False under ALG_SOUND=dummy, and false where no output device exists.
⚠️ Nearly everything still works when it is False. Play takes exactly as long, Score answers the same notes, and LoadSound still decodes the file — which is what lets this unit's tests assert a tune's timing in silence, the same bargain SDL_VIDEODRIVER=dummy strikes for graph.
The one exception is PlaySound, which answers False because there is no voice for it to sound on. A program that checks that return should ask this first rather than treating it as a failure.
SetVolume
How loud the tone is, from 0 to 255.
procedure SetVolume (Level : Integer);
Neither Turbo Pascal's nor BASIC's — the PC speaker had one volume, which was all of it. A value outside the range is clamped rather than refused, there being no wrong answer to make louder than loudest.
⚠️ It applies to the tone, not to a sample. A sound effect started by PlaySound carries its own level, so SetVolume does not touch one.
Raises nothing — every Integer is a level.
uses sound;
uses crt;
SetVolume (64); // a quarter of the way up
Sound (440);
Delay (50);
NoSound ();
SetVolume (900); // clamped to 255, not refused
// crt shadows WriteLn, so the console is reached through System.
System.WriteLn ('volume accepted');
Shell
volume accepted
See also
Example
See Sound.
Split
extension function — unit strings
Function
Returns the pieces of a string between occurrences of a separator, as a List.
Declaration
extension function Split (S : String, By : String) : List;
Remarks
Every piece is kept, the empty ones included: a separator at either end leaves an empty piece there, and two separators together leave one between them. That is what makes Join undo Split for every string and every separator; dropping the empties would be a different routine wearing the same name.
A separator that does not occur answers a List of one piece, S itself, so a caller need not ask first. The separator may be of any length.
An empty separator raises, there being no sequence of pieces that would mean it.
To find one occurrence rather than cut at all of them, the core's own Pos answers the index of the first, or −1 when there is none — and takes a start index, so Pos (S, What, From) walks the occurrences without slicing. That is what this routine does internally, in one pass over S.
Both spellings work: Split (S, ',') and S.Split (',').
Raises Split needs a separator. for an empty separator.
See also
Example
uses strings;
var Fields := 'red,green,blue'.Split (',');
WriteLn (Fields.Length);
WriteLn (Str (Fields[1]));
// A separator that does not occur answers one piece, the whole string.
WriteLn ('no commas here'.Split (',').Length);
// Every piece is kept, which is what makes Join undo Split.
WriteLn ('[' + ',a,'.Split (',').Join ('|') + ']');
WriteLn ('a,,b'.Split (',').Join (','));
Shell
3
green
1
[|a|]
a,,b
SplitPath
functions — unit file
Function
Takes a path apart into its directory, name and extension, and puts a relative one back together as an absolute.
Declaration
function SplitPath (Path : String) : PathParts;
function FullPath (Path : String) : String;
// PathParts, readable
Dir : String up to and including the last separator
Name : String the bare name, with no extension
Ext : String from the last dot, including it
function Text () : String the three put back together
Remarks
Turbo Pascal's FSplit, which wrote into three var parameters. This answers the one object they become — the same trade time makes for GetDate.
⚠️ The three concatenate back into the path they came from, for every input. Dir keeps its trailing separator and Ext its leading dot precisely so that they do, and Text () is that concatenation. A test asserts the round trip over thirteen shapes.
A dot that begins the name is part of the name, so .profile is a name with no extension rather than the other way round. Only the last dot separates, so archive.tar.gz has .gz.
A trailing separator gives an empty Name, and a path with no separator an empty Dir.
Raises nothing — every string is a path as far as this is concerned.
See also
Example
uses file;
var S := SplitPath ('/tmp/archive.tar.gz');
WriteLn ('dir: ', S.Dir);
WriteLn ('name: ', S.Name);
WriteLn ('ext: ', S.Ext);
WriteLn ('back: ', S.Text ());
var H := SplitPath ('.profile');
WriteLn ('a leading dot is a name: [', H.Name, '] [', H.Ext, ']');
Shell
dir: /tmp/
name: archive.tar
ext: .gz
back: /tmp/archive.tar.gz
a leading dot is a name: [.profile] []
FullPath
A path made absolute, with . and .. resolved away.
function FullPath (Path : String) : String;
Turbo Pascal's FExpand. A relative path is taken against the working directory, which the core answers with GetDir [RT-026]; an absolute one is only tidied.
Tidying means repeated separators collapse, a . component goes, and a .. component removes the one before it. A .. at the root stays at the root rather than climbing past it.
⚠️ This asks the filesystem nothing. It does not resolve symbolic links and does not require the path to exist — which is what makes it usable on a name a program is about to create.
Raises nothing.
Example
uses file;
WriteLn (FullPath ('/a/b/../c'));
WriteLn (FullPath ('/a/./b//c'));
WriteLn (FullPath ('/..'));
WriteLn (FullPath ('/no/./such/../such/place'));
WriteLn (FullPath ('x.txt') = GetDir () + '/x.txt');
Shell
/a/c
/a/b/c
/
/no/such/place
true
Sqr
function — unit math
Function
Returns the square of its argument.
Declaration
function Sqr (X);
Remarks
The result has the same type as X, so an Integer squares to an Integer and a Double to a Double. Integers being unbounded, the square of a value near the machine width grows rather than wrapping.
Untyped, with the same consequence for a declared variable as Abs.
Raises Operands must be numbers. for an argument the multiplication cannot take.
Note that Sqr squares and Sqrt takes the root — the names are close and the operations are opposite.
See also
Example
uses math;
WriteLn (Sqr (12));
WriteLn (Sqr (2.5));
Shell
144
6.25
Sqrt
function — unit math
Function
Returns the non-negative square root of its argument.
Declaration
function Sqrt (X : Double) : Double;
Remarks
A negative argument answers NaN rather than raising, which is libm's behavior and not this unit's choice. NaN is not equal to itself, which is how to detect it.
A foreign declaration onto libm's sqrt.
See also
Example
The hypotenuse of a 3–4–5 triangle, which shows Sqr and Sqrt together.
uses math;
WriteLn (Sqrt (2.0));
var A := 3.0;
var B := 4.0;
WriteLn (Sqrt (Sqr (A) + Sqr (B)));
Shell
1.4142135623730951
5.0
SurfaceAt
function — unit graph and crt
Function
The topmost surface under a point, or nil.
Declaration
function SurfaceAt (X : Integer, Y : Integer) : Any;
Remarks
The stack decides: highest Order wins, and a tie goes to whichever surface was made later — the same rule that decides what is drawn over what.
⚠️ The root grid covers the whole screen, so a point over nothing else answers it rather than nil. Only a point off the screen entirely answers nil.
An invisible surface — Alpha of 0 — is under nothing.
Coordinates are the screen's own space: logical pixels in graph, cells in crt. In graph a Window is measured in cells and a ViewPort in pixels, but both live in the one logical space, so both answer here.
ReadEvent does this for every mouse event already and puts the answer in Event.Surface, along with the point in that surface's own coordinates — so this is for asking about a point nothing has clicked.
Raises Graph is not open. or Crt is not open.
See also
EnableMouse, Event, ReadEvent, ViewPort, Window
Example
See EnableMouse.
TextBackground
procedure — unit graph and crt
Function
Sets the background cells are painted with.
Declaration
procedure TextBackground (Color : Integer); // the screen
procedure TextBackground (W : Window, Color : Integer); // that window
Remarks
TextBackground (W, Color) is an alias of W.TextBackground, setting that window's background alone.
Transparent — the default — leaves everything beneath the glyph visible, which is the merged world's natural state. Any RGB color makes the cell opaque, which is what a menu bar or a readable HUD over a busy scene wants.
The setting applies to cells painted from now on; nothing already on the grid changes.
Raises TextBackground wants a color or Transparent. above White — Blink belongs to TextColor and is refused here — and for a negative that is not Transparent.
See also
Example
uses graph;
InitGraph (320, 200, 'bg', False);
TextBackground (Blue);
TextColor (Yellow);
Write ('classic');
System.WriteLn ('painted');
CloseGraph ();
Shell
painted
TextColor
procedure — unit graph and crt
Function
Sets the ink celled text draws with.
Declaration
procedure TextColor (Color : Integer); // the screen
procedure TextColor (W : Window, Color : Integer); // that window
Remarks
TextColor (W, Color) is an alias of W.TextColor, setting that window's ink alone.
Any RGB Integer; the sixteen color constants are the classic vocabulary, and adding Blink makes the ink blink. The default is LightGray, which is what a text mode woke up in.
Ink is the one thing a cell always has, so Transparent raises TextColor cannot be transparent.
See also
Example
See TextBackground, which sets both.
TextCols
function — unit graph and crt
Function
Returns the grid's width in cells.
Declaration
function TextCols () : Integer;
Remarks
⚠️ In crt these answer the terminal itself, asked afresh, so a resized window changes them between one frame and the next. graph's is a logical grid of a size the program chose.
80, until TextMode says otherwise. The grid is logical, not a division of the window: an 80 × 25 screen is 80 × 25 in every window, scaled to fit at present time. A wide (CJK) glyph occupies two of its cells.
Raises Graph is not open. without a window.
See also
Example
uses graph;
InitGraph (1280, 800, 'classic', False);
System.WriteLn (TextCols ());
System.WriteLn (TextRows ());
CloseGraph ();
Shell
80
25
TextJustify
constants — unit graph
Function
The justifications SetTextJustify takes.
Declaration
const LeftText := 0; const BottomText := 0;
const CenterText := 1; const TopText := 2;
const RightText := 2;
Remarks
Turbo Pascal's five names and its five values, CenterText serving both axes.
⚠️ BottomText and LeftText are both zero, as they were there, so passing one where the other belongs is not caught — SetTextJustify sees the number, not which name was written. It is worth reading the second argument twice.
The horizontal three say which end of the text meets the point; the vertical three say which edge of the line does. LeftText, TopText is what a fresh viewport holds.
See also
Example
See SetTextJustify.
TextMode
procedure — unit graph
Function
Chooses the grid: columns by rows of cells, whatever the window's size.
Declaration
procedure TextMode (Cols : Integer, Rows : Integer);
Remarks
The screen clears, the cursor homes, and the colors return to their defaults — which is what Turbo Pascal's TextMode did on a mode change, and the behavior a program switching modes wants.
Turbo Pascal's argument was a video-card mode — CO80, CO40, Font8x8 — because the grid was a register setting. Here the grid is logical, so the argument is simply the grid: the two classics are TextMode (80, 25) and TextMode (40, 25), and nothing stops TextMode (132, 50).
⚠️ The window does not change; the grid is scaled to it. A side effect worth having: an 80 × 25 grid shown in a 4:3 window — 640 × 480, say — displays its cells at 1:2.4, which is exactly how real text mode looked on a 4:3 tube, whose pixels were not square.
Raises Graph is not open. without a window, and TextMode needs a positive grid. for a Cols or Rows of zero or less.
See also
Example
uses graph;
InitGraph (640, 480, 'modes', False);
System.WriteLn (TextCols ());
TextMode (40, 25);
System.WriteLn (TextCols ());
System.WriteLn (TextRows ());
CloseGraph ();
Shell
80
40
25
TextRows
function — unit graph and crt
Function
Returns the grid's height in cells.
Declaration
function TextRows () : Integer;
Remarks
⚠️ In crt these answer the terminal itself, asked afresh, so a resized window changes them between one frame and the next.
25, until TextMode says otherwise, on the same reasoning as TextCols, which shows both.
Raises Graph is not open. without a window.
See also
Example
See TextCols.
TextSettings
classes — unit graph
Function
The text state a viewport is holding, and where it sits.
Declaration
constructor TextSettings (Direction : Integer, CharSize : Integer,
Horiz : Integer, Vert : Integer, MultX : Integer,
DivX : Integer, MultY : Integer, DivY : Integer);
Direction, CharSize : Integer what SetTextStyle set
Horiz, Vert : Integer what SetTextJustify set
MultX, DivX, MultY, DivY : Integer what SetUserCharSize set
constructor ViewSettings (X1 : Integer, Y1 : Integer, X2 : Integer,
Y2 : Integer, Clip : Boolean);
X1, Y1, X2, Y2 : Integer the corners, inclusive
Clip : Boolean always True
Remarks
Turbo Pascal's TextSettingsType and ViewPortType, answered by GetTextSettings and GetViewSettings rather than written into a var record — the same reasoning as ArcCoords and FillSettings. Every field is named for the argument that sets it, so a saved state goes back through the setters without translation.
⚠️ TextSettings has no Font field. A font here is a glyph file chosen by InstallUserFont rather than one of a numbered handful, so there is no number to report.
⚠️ CharSize is 0 while a SetUserCharSize ratio is in force, which is Turbo Pascal's convention for the same situation. The four ratio terms always say what is actually magnifying, so the zero hides nothing and either setter can restore what it set.
ViewSettings reports where a viewport is rather than a clipping rectangle to be moved: there is one screen in Turbo Pascal and a stack of objects here. Its corners are inclusive, so X2 is X + W - 1 — the arithmetic worth having a verb for. Clip is always True, a viewport's edge being its clip with no way to ask otherwise.
See also
ArcCoords, FillSettings, GetTextSettings, SetTextStyle, ViewPort
Example
See GetTextSettings.
TextWidth
functions — unit graph
Function
How much room a string would take up, in pixels.
Declaration
function TextWidth (Text : String) : Integer; // the background
function TextWidth (V : ViewPort, Text : String) : Integer; // that viewport
function TextHeight (Text : String) : Integer; // the background
function TextHeight (V : ViewPort, Text : String) : Integer; // that viewport
Remarks
The viewport forms are aliases of V.TextWidth and V.TextHeight.
⚠️ This has to be asked for; it cannot be worked out. Glyphs are not one width — a CJK ideograph is twice a Latin letter, an emoji likewise, and a code the font lacks is half a cell — so Length (Text) * CellWidth () is wrong for anything but plain ASCII, and the per-glyph widths are private to the unit.
TextWidth (V, 'A') // 16
TextWidth (V, '你') // 32, on the same font
What it measures is the box the text would occupy on the surface, in the turn and magnification SetTextStyle is holding. Width and height are the surface's axes rather than the string's, so a quarter turn swaps them:
| turn | TextWidth | TextHeight |
|---|---|---|
| 0, 180 | the glyphs end to end | one line of the font |
| 90, 270 | one line of the font | the glyphs end to end |
Both scale with CharSize. Half a turn runs the text the other way but occupies the same box as none.
TextWidth is exactly what OutText advances the position by, computed once and shared, so laying text out by hand lands where drawing it would. Turned a quarter, the advance is TextHeight instead — it is the one along the direction of travel.
The screen-wide forms measure the background, which has no SetTextStyle of its own and so never turns or magnifies.
An empty string occupies nothing, both ways. TextHeight takes a string it barely consults — the font is one height throughout — but takes one as Turbo Pascal's did, so that an empty string can answer nothing and so a font of varying height would not change the signature.
Raises CloseGraph has closed this surface. on a viewport whose window has gone, and Graph is not open. for the screen-wide forms without a window.
See also
CellWidth, OutText, OutTextXY, SetTextStyle
Example
uses graph;
InitGraph (640, 480, 'measure', False);
var V := ViewPort (40, 40, 300, 120, 1);
// Length times a cell width is wrong the moment a string leaves ASCII: a CJK
// ideograph is twice a Latin letter, and the font knows which is which.
System.WriteLn ('A is ', TextWidth (V, 'A'), ' wide');
System.WriteLn ('你 is ', TextWidth (V, '你'), ' wide');
System.WriteLn ('a line is ', TextHeight (V, 'A'), ' tall');
// Centering needs the real width, so it needs to be asked for.
var Caption := 'Hello 你好';
var Left := (300 - TextWidth (V, Caption)) div 2 + 1;
SetColor (V, LightCyan);
OutTextXY (V, Left, 50, Caption);
Show (V);
System.WriteLn ('centered at ', Left, ' of 300');
// Turned a quarter, the same string occupies the other way about.
SetTextStyle (V, 90, 1);
System.WriteLn ('turned: ', TextWidth (V, Caption), ' by ',
TextHeight (V, Caption));
CloseGraph ();
Shell
A is 16 wide
你 is 32 wide
a line is 32 tall
centered at 71 of 300
turned: 32 by 160
Trim
extension function — unit strings
Function
Returns its argument without the whitespace at either end.
Declaration
extension function Trim (S : String) : String;
Remarks
Whitespace is the space and the five control characters above it that a text file uses as such — tab, newline, vertical tab, form feed and carriage return. Nothing else, which is the only answer that can be stated exactly: the Unicode space separators are a table, and strings has none.
Whitespace inside the string is left alone; only the ends are touched. A string of nothing but whitespace answers the empty string, which is also what trimming the empty string answers.
The ends are found by index rather than by building, so a string needing no trimming is copied once and never examined character by character.
Both spellings work: Trim (S) and S.Trim (). The second is what makes a chain read in the order it happens — S.Trim ().Upper ().
Never raises.
See also
Example
uses strings;
WriteLn ('[' + Trim (' padded ') + ']');
var Messy := #9 + ' tabs and spaces ' + #10;
WriteLn ('[' + Messy.Trim () + ']');
WriteLn ('[' + Trim (' ') + ']');
Shell
[padded]
[tabs and spaces]
[]
Trunc
function — unit math
Function
Returns the integer part of its argument, discarding any fractional part.
Declaration
function Trunc (X : Double) : Integer;
Remarks
Truncation is toward zero, so Trunc (-3.7) is -3 rather than -4, which differs from flooring for a negative argument. Truncating toward zero is what makes Trunc and Int one operation in two return types, and what leaves Frac carrying the sign of its argument.
The result is an Integer proper, not a Double carrying a whole number, so it may be used wherever an Integer is wanted — added to one, passed to Odd, rendered by Str without a .0.
An Integer argument is accepted as readily as a Double, and answers itself.
⚠️ Every finite Double is answered exactly, however large. An Algol-24 Integer is unbounded, so there is no width for a result to exceed. Trunc (1.0E300) is the exact 301-digit integer — not a refusal, and not an approximation.
That takes two paths, and they meet without a seam. Below 2^63 a C conversion does the truncating. At or above it a Double has no fractional bits left and is already a whole number, so there is nothing to truncate: the value is rebuilt from its mantissa and exponent using unbounded Integer arithmetic.
Only two arguments are refused, neither having an integer to answer with:
| Argument | Result |
|---|---|
NaN | raises Trunc of NaN. |
| either infinity | raises Trunc of an infinity. |
Unlike the other foreign-backed routines here, Trunc does not call libm for its main primitive. libm's trunc returns a double, and a foreign declaration must name a C function whose real signature is the one wanted, so alg_trunc is written in mathffi.c and built by ./build.sh — along with the two calls that take a Double apart into mantissa and exponent.
See also
Example
uses math;
WriteLn (Trunc (3.7));
WriteLn (Trunc (-3.7));
WriteLn (Trunc (2.999999));
WriteLn (Trunc (7.5) + Trunc (2.5));
// Far beyond what a C conversion could answer, and still exact.
WriteLn (Trunc (1.0E30));
try
WriteLn (Trunc (1.0 / 0.0));
except
on e : String do WriteLn (e);
end
Shell
3
-3
2
9
1000000000000000019884624838656
Trunc of an infinity.
Upper
extension function — unit strings
Function
Returns its argument with the ASCII lowercase letters raised.
Declaration
extension function Upper (S : String) : String;
Remarks
⚠️ This is the core's own ToUpper, with the extension spelling added. It exists so that S.Upper () composes in a chain, which a built-in function cannot; ToUpper (S) is the same call and needs no uses.
ASCII only, which is the core's decision rather than this unit's — and the right one. Unicode case mapping is a table and not even character-to-character: ß uppercases to SS. Every character outside a–z comes back exactly as it went in, accented letters, Greek, Cyrillic and emoji alike.
Both spellings work: Upper (S) and S.Upper ().
Never raises.
See also
Example
uses strings;
WriteLn (Upper ('hello'));
WriteLn ('mixed CASE 123'.Upper ());
// ASCII only: the accented letter comes back as it went in.
WriteLn ('café'.Upper ());
WriteLn (' trimmed first '.Trim ().Upper ());
Shell
HELLO
MIXED CASE 123
CAFé
TRIMMED FIRST
UtcOffset
function — unit time
Function
Returns the host's offset from UTC in seconds at a given moment.
Declaration
function UtcOffset (Epoch : Double) : Integer;
Remarks
Positive east of Greenwich.
⚠️ It takes a moment because the offset is not a constant. A zone observing daylight saving has two, and which applies depends on the date. Asking at the wrong instant is the usual way zone arithmetic goes wrong, so there is no argument-free form to reach for.
This is the one thing in the unit a program could not work out for itself. Leap years are a closed rule and the calendar arithmetic could be hand-rolled; the zone lives in the host's database and changes by legislation.
Never raises. A host on UTC and a host whose zone could not be read both answer zero.
See also
Example
uses time;
// The offset is a fact about the host, so only what is true everywhere is
// printed: every real zone is a whole number of minutes from UTC, and none
// is further than fourteen hours.
WriteLn (UtcOffset (0.0) mod 60);
WriteLn (UtcOffset (0.0) >= 0 - 50400 and UtcOffset (0.0) <= 50400);
// And a local reading is the UTC reading of the shifted instant.
var E := 1234567890.0;
WriteLn (At (E).Text () = UtcAt (E + UtcOffset (E)).Text ());
Shell
0
true
true
ViewPort
class — unit graph
Function
A positioned, sized pixel surface with a place in the stack.
Declaration
constructor ViewPort (X : Integer, Y : Integer, W : Integer, H : Integer,
Order : Integer);
procedure MoveTo (PX : Integer, PY : Integer);
procedure PutPixel (PX : Integer, PY : Integer, Color : Integer);
function GetPixel (PX : Integer, PY : Integer) : Integer;
procedure FloodFill (X : Integer, Y : Integer, Border : Integer);
function GetArcCoords () : ArcCoords;
function GetTextSettings () : TextSettings;
function GetViewSettings () : ViewSettings;
procedure GraphDefaults ();
procedure SetPalette (Palette : Map);
function GetPalette () : Map;
procedure SetWriteMode (Mode : Integer);
function GetWriteMode () : Integer;
procedure SetUserCharSize (MultX : Integer, DivX : Integer,
MultY : Integer, DivY : Integer);
function GetImage (X1 : Integer, Y1 : Integer, X2 : Integer,
Y2 : Integer) : Image;
procedure PutImage (X : Integer, Y : Integer, Img : Image, Mode : Integer);
function GetFillPattern () : List;
function GetFillSettings () : FillSettings;
function GetLineSettings () : LineSettings;
procedure SetBkColor (Color : Integer);
function GetBkColor () : Integer;
procedure SetTextJustify (Horiz : Integer, Vert : Integer);
function TextWidth (Text : String) : Integer;
function TextHeight (Text : String) : Integer;
procedure Clear ();
procedure OutText (Text : String);
procedure OutTextXY (PX : Integer, PY : Integer, Text : String);
procedure SetTextStyle (Direction : Integer, CharSize : Integer);
procedure Show ();
// the pen -- see Line
procedure SetColor (Color : Integer);
function GetColor () : Integer;
procedure SetLineStyle (Style : Integer, Pattern : Integer, Thickness : Integer);
procedure PenTo (PX : Integer, PY : Integer);
procedure PenRel (DX : Integer, DY : Integer);
function GetX () : Integer;
function GetY () : Integer;
procedure Line (X1 : Integer, Y1 : Integer, X2 : Integer, Y2 : Integer);
procedure LineTo (PX : Integer, PY : Integer);
procedure LineRel (DX : Integer, DY : Integer);
procedure Rectangle (X1 : Integer, Y1 : Integer, X2 : Integer, Y2 : Integer);
// readable, and the first four settable
X, Y : Integer the top-left pixel on screen
Order : Integer under the root grid when negative, over it when positive
Alpha : Integer 0 invisible .. 255 opaque
W, H : Integer the size, fixed at creation
Dir, Size : Integer the text turn and magnification -- see SetTextStyle
HJust, VJust : Integer the justification -- see SetTextJustify
Remarks
Turbo Pascal's SetViewPort named a clipped drawing region; this is that grown into an object. X, Y place it in the logical space the grid lives in — the same space a Window's cells are measured in, so the two scale together and a chart placed inside a window stays inside it at every window size; see CellWidth. W, H size it, and Order stacks it — negative under the root grid, positive over it, and 0 is refused because that is the root grid's own.
⚠️ Coordinates inside a viewport are local, counting from 1: 1, 1 is its top-left corner, not the screen's. That is what makes the drawing portable — MoveTo the viewport and everything on it moves, nothing redraws.
⚠️ Local is also the clip. A pixel outside the viewport is discarded silently rather than raising, so a drawing cannot scribble on its neighbors and there is no clipping rectangle to maintain.
The pen — Line and its family — draws in these coordinates too. MoveTo moves the viewport; PenTo moves the pen.
Unpainted pixels are transparent, so a fresh viewport shows everything beneath it; Alpha ghosts the whole surface at once. Both Alpha and Order may be assigned after creation — reordering is bring-to-front.
OutTextXY draws free text: a graphic that happens to be letters, with no cursor, no wrap, and no text verb that will ever erase it — see Write for the celled kind. OutText draws at the viewport's own current position and advances it. SetTextStyle turns that text by a quarter and magnifies it, neither of which celled text can have.
Drawing does not appear until something presents; Show is that, and ReadKey does it too while waiting.
CloseGraph invalidates every surface: a method called afterward raises CloseGraph has closed this surface.
Raises Graph is not open. without a window, Order 0 is the screen's., and ViewPort needs a positive size.
See also
Its methods each have a free-function alias with an entry of its own: Arc, Bar, Bar3D, Circle, DrawPoly, Ellipse, FillEllipse, FillPoly, Line, LineTo, PieSlice, Sector, LineRel, SetFillStyle, Rectangle, PenTo, PenRel, GetX, GetY, SetColor, GetColor, SetLineStyle, PutPixel, GetPixel, FloodFill, GetArcCoords, OutText, OutTextXY, SetTextStyle, Show, MoveTo, ClearViewPort, TextWidth, SetBkColor, SetTextJustify, GetFillPattern, GetFillSettings, GetLineSettings, GetImage, PutImage, GetTextSettings, GetViewSettings, GraphDefaults, SetWriteMode, GetWriteMode, SetUserCharSize, SetPalette, GetPalette.
Clear is the method ClearViewPort (V) reaches.
Example
uses graph;
InitGraph (640, 480, 'viewport', False);
var Chart := ViewPort (100, 60, 200, 120, 2);
Chart.PutPixel (1, 1, Yellow);
Chart.PutPixel (200, 120, Yellow);
Chart.PutPixel (201, 1, Red);
Chart.OutTextXY (8, 8, 'a label');
Chart.Show ();
System.WriteLn (Chart.W);
System.WriteLn (Chart.H);
System.WriteLn (Chart.Order);
Chart.Order := -1;
System.WriteLn (Chart.Order);
CloseGraph ();
Shell
200
120
2
-1
WhereX
function — unit graph and crt
Function
Returns the cursor's column.
Declaration
function WhereX () : Integer; // the screen
function WhereX (W : Window) : Integer; // that window
Remarks
One-based, like GotoXY, which shows it read back: 1 at the left edge, TextCols () at the right. WhereX (W) is an alias of W.WhereX, answering that window's cursor instead.
Raises Graph is not open. without a window.
See also
Example
WhereY
function — unit graph and crt
Function
Returns the cursor's row.
Declaration
function WhereY () : Integer; // the screen
function WhereY (W : Window) : Integer; // that window
Remarks
One-based. Everything said of WhereX holds here.
See also
Example
Window
class — unit graph and crt
Function
A rectangle of text cells with a place in the stack.
Declaration
constructor Window (X1 : Integer, Y1 : Integer, X2 : Integer, Y2 : Integer,
Order : Integer);
procedure MoveTo (Col : Integer, Row : Integer);
procedure GotoXY (Col : Integer, Row : Integer);
function WhereX () : Integer;
function WhereY () : Integer;
procedure TextColor (Color : Integer);
procedure TextBackground (Color : Integer);
procedure HighVideo ();
procedure LowVideo ();
procedure NormVideo ();
procedure Write (Text : String);
procedure WriteLn (Text : String);
procedure ClrEol ();
procedure Clear ();
procedure SetPalette (Palette : Map);
function GetPalette () : Map;
procedure DelLine ();
procedure InsLine ();
// readable, and Order and Alpha settable
X1, Y1, X2, Y2 : Integer the corner cells, inclusive
Cols, Rows : Integer the size in cells
Order : Integer under the root grid when negative, over it when positive
Alpha : Integer 0 invisible .. 255 opaque
Remarks
crt's Window is the same class on a terminal: its own cells, its own cursor, its own colors, stacked by Order. It has no Alpha blending — a cell holds one character — so Alpha there is 0 for invisible and anything else for visible, and no PixelLeft/PixelTop, there being no pixels to place a viewport against.
Turbo Pascal's Window (X1, Y1, X2, Y2) grown into an object. The corners are cells of the root grid's space, inclusive and one-based, so Window (1, 1, 80, 25) is the whole screen and Window (10, 5, 49, 19) is 40 × 15 cells.
⚠️ A window is a terminal of its own. It carries the whole text vocabulary as methods, each acting on its own cells: its own cursor (1, 1 is its corner), its own ink and background, its own blink ink, and its own scrolling — WriteLn at the window's bottom row scrolls that window's cells and nothing else's. ClrScr clears it alone.
That is the design's one rule, and where it pays: B.ClrEol erases B's prose and cannot touch a chart on another surface, however they overlap on screen.
Order stacks it — negative under the root grid, positive over it, 0 refused as the root grid's own — and ties stack by creation, earlier beneath later. Because text is a stackable surface, a window may sit over a graphic that is itself over other text, which no single text plane can express.
MoveTo drags the window, keeping its size; any position is allowed, off the grid included, and what falls outside is clipped at present time.
⚠️ The wrap is deferred, as text mode always had it: a line that exactly fills the last column leaves the cursor resting on that column with the wrap owed, and it happens only when another character arrives. Without this a window's own bottom border would scroll the window as it was drawn. GotoXY and ClrScr cancel a wrap that is owed.
An InstallUserFont of a different cell size rebuilds every live window at the same columns and rows — the cells come back empty.
CloseGraph invalidates every surface: a method called afterward raises CloseGraph has closed this surface.
Raises Graph is not open. without a window, Order 0 is the screen's., and Window wants 1 <= X1 <= X2 and 1 <= Y1 <= Y2.
See also
Its methods each have a free-function alias with an entry of its own: Write, WriteLn, GotoXY, WhereX, WhereY, TextColor, TextBackground, HighVideo, LowVideo, NormVideo, ClrEol, ClrScr, MoveTo, DelLine, InsLine, SetPalette, GetPalette.
Clear is the method ClrScr (W) reaches.
Example
examples/surfaces.a24 drags one window over another's chart; this shows that a window's cursor and the screen's are different things.
uses graph;
InitGraph (640, 480, 'windows', False);
var W := Window (10, 5, 49, 19, 1);
W.TextBackground (Blue);
W.Clear ();
W.Write ('its own cursor and colors');
System.WriteLn (W.Cols);
System.WriteLn (W.Rows);
System.WriteLn (W.WhereX ());
System.WriteLn (WhereX ());
W.MoveTo (2, 2);
System.WriteLn (W.X2);
CloseGraph ();
Shell
40
15
26
1
41
Write
procedures — unit graph and crt
Function
Writes to the screen's text grid, advancing its cursor.
Declaration
procedure Write (Values : List of Any); // the screen, or a leading Window
procedure WriteLn (Values : List of Any);
Remarks
⚠️ In crt, System.Write reaches the same terminal the unit is painting, so a call to it while the screen is up lands in the middle of that screen. In graph the two are different devices and there is no conflict.
The screen is the root Window, and these are its Write and WriteLn — celled text that wraps at the last column, scrolls the grid and only the grid at the bottom row, and is what ClrEol and ClrScr erase. A #10 in a value starts a new row, a wide (CJK) glyph takes two cells, and WriteLn () is a bare newline.
Variadic, and each value rendered as Str renders it, which is the built-in's own contract [RT-015] kept: Write ('a', 42, ' ', 3.5) writes a42 3.5.
⚠️ These shadow the built-ins for any program that says uses graph, and that is the intent — in a graphics program WriteLn should reach the window rather than standard output. The console remains reachable under its own unit's name:
WriteLn ('this lands in the window');
System.WriteLn ('this lands on the console');
System.Write and System.WriteLn are the built-ins exactly as they were, variadic and untouched, and every example in this reference uses them to report a value while a window is open. Nothing is lost by the shadowing; it only has to be named.
Free, pixel-placed text is OutTextXY's job, and the two never meet. A Window has its own Write and WriteLn writing into its own cells.
Raises Graph is not open. without a window.
See also
ClrScr, GotoXY, TextColor, Window
Example
uses graph;
InitGraph (640, 480, 'write', False);
Write ('Hi ', 42, ' 你好');
WriteLn ();
System.WriteLn (WhereX ());
System.WriteLn (WhereY ());
CloseGraph ();
Shell
1
2