Copyright: TMT Pascal Help, Copyright (c) 1995-2002 by TMT Development Corporation


The TMT Pascal Language Description

Features

Implementation Issues

Pascal Language Structure

Types

Declarations

Expressions

Statements

Programs and Units

Procedures and Functions

OOP Extensions

Open Arrays

User Defined Operators

User Defined Operators

User Defined Reader Procedure

User Defined Writer Procedure

Built-in Assembler

Run-time Error Codes


Features

Overview

The TMT Pascal compiler is a fast compiler for the Pascal language. The compiler emits 32-bit code and supports many language extensions from Borland Pascal (BP), as well as more powerful new extensions.

TMT Pascal brings new life to the 32-bit MS DOS applications.

Language extensions

The TMT Pascal compiler supports a new enhanced dialect of the PASCAL language. This dialect fully covers the Borland Pascal language and has additional powerful extensions such as:

•	C/C++ and ADA-style comments

•	“ +:=” and “-:=” C-style operators

•	Local declarations

•	Multidimensional open arrays

•	Operator overloading

•	Unnamed procedural blocks

•	Interface/Implementation blocks declaration in main program body

•	Intel(tm) MMX and AMD(tm) 3DNow! technologies support


Implementation Issues

This part of help describes the following implementation issues:

Memory Organization

Calling Conventions

Limitations


Memory Organization

The TMT Pascal compiler uses the TMTSTUB (based on WDOSX) and PMWSTUB (based on PMODE/W) extenders for a protected-mode program.

The segment registers are not used in protected mode. Instead all address space is separated into 4Kb pages.

You do not need to add a special _zero variable to get access to the physical addresses.

For example:

procedure clr_video(filler: char);

var

  i: Integer;

begin

  for i := 0 to 80 * 25 - 1 do

  mem[$B8000 + i * 2] := filler;

end;

This procedure fills the video memory of the VGA adapter with the filler symbol.

Note that the linear address $B8000 is used as the physical address - not the segment address $B800.

Some another special variables are described in the SYSTEM unit. The _psp variable contains the logical 32-bit address of the PSP of the program, and the _environ variable contains the environment address.

Although you can access the interrupt vectors by using this method, we do not suggest doing this.

Also keep in mind that MS-DOS interrupt handlers use memory addresses in the 1st Mb of physical memory while your program and its data are loaded beyond the 1st Mb. The TMTSTUB intercepts and correctly handles some, but not all, calls to MS-DOS. Thus, if you are using Intr or MsDos calls, or call MS-DOS from the assembler, you will need to modify the code.

Absolute memory addressing Mem, MemW, MemL, and MemD pseudo-arrays may be used in BP-compatible manner:

  var x: type absolute seg:offs

  Mem[seg:offs]

Here the effective address is computed as seg*16+offs. The Ptr(seg, offs) function works similarly. The Seg(v) function still always returns 0.

These new functions should substantially simplify the conversion of the programs that use absolute addressing.

An example of using these functions can be found in file TMTPL\SAMPLES\MSDOS\FLAME\FLAME.PAS

See also:

PMODE/W API


Calling Conventions

Calling conventions match those in Borland Pascal with the following differences:

•	all parameters use 4 bytes on the stack, or a multiple of 4 (BP:2)

•	all procedures must preserve the contents of registers ebx, ecx, edx, ds, and es!

•	the direction bit should be cleared after the exit from a procedure, if it has been modified by the procedure.

Standard Calling Conventions

To call external procedures written for different languages, TMT Pascal provides the conv operator. The conv operator should be used in the function (procedure) declaration to define a calling convention, which in turn will be used to call a declared function (procedure):

Syntax:

[function] conv conv_method FunctionName [Arguments] : ReturnType;

where conv_method is a constant, which defines the calling conversion to be used. The System units contains the following constants to define a conventional method:

const

// Base calling conventions to construct any possible convention

  arg_reverse        = [0];

  arg_proc_16        = [2];

  arg_noregsave      = [3];

  arg_no_drop_1      = [4];

  arg_no_drop_2      = [5];

  arg_no_drop_3      = arg_no_drop_1 + arg_no_drop_2;

  arg_no_drop_4      = [6];

  arg_no_drop_5      = arg_no_drop_1 + arg_no_drop_4;

  arg_no_drop_6      = arg_no_drop_2 + arg_no_drop_4;

  arg_no_drop_all    = [4..6];

  arg_IO_test        = [8];

  arg_save_edi       = [9];

  arg_save_esi       = [10];

  arg_no_fp_on_stack = [11];

  arg_based          = [12];

// Composite calling conventions

  arg_pascal     = arg_noregsave;

  arg_stdcall    = arg_reverse + arg_noregsave + arg_save_edi +

                   arg_save_esi;

  arg_cdecl      = arg_reverse + arg_no_drop_all;

  arg_os2        = arg_cdecl + arg_noregsave;

  arg_os2_16     = arg_proc_16 + arg_no_drop_all + arg_noregsave;

The arg_pascal convention passes parameters from left to right; that is, the leftmost parameter is evaluated and passed first and the rightmost parameter is evaluated and passed last. The arg_cdecl, arg_stdcall, arg_os2 and arg_os2_16 conventions pass parameters from right to left. For all conventions except arg_cdecl, the procedure or function removes parameters from the stack upon returning. With the arg_cdecl convention, the caller must remove parameters from the stack when the call returns. The calling conventions are summarized in the following table:

Directive                      Order               Cleanup           Registers

arg_pascal	Left-to-right	Function	No

arg_cdecl	Right-to-left	Caller	No

arg_stdcall	Right-to-left	Function	No

Additional Calling Conventions

arg_proc_based: forces 64-bit sized extended procedure types (see also: Procedural Value)

arg_no_fp_on_stack: forces old-style floating-point calling conventions for compatibility with older versions of the compiler.


Limitations

1) Mark and Release are not implemented.

2) The Inline operator is implemented in a partial form:

Inline(byte/byte/...);

References to variables/constants are not allowed.

3) Import of object modules does not support all 32-bit object formats. We recommend using TASM which is fully supported, except the usage of SEG addresses.

4) Complex type is not implemented.

5) Constants of Extended type are not supported.

6) The reserved word Packed has no effect (ignored) in TMT Pascal. Use $OA: Objects and Structures Align Switch to switch on or switch off objects and structures alignment.


Pascal Language Structure

TMT Pascal programs are to be written either the TMT Pascal IDE editor or an editor of your choice. The source files created by your editor must be standard ASCII text. All characters within the range of 32 to 127 (decimal) are valid. Control characters (characters below 32 decimal) are treated as spaces.

Tokens and Identifiers

Reserved Words

Operators and Delimiters

Constants

Program Comments


Tokens and Identifiers

Contiguous characters in a source file, not including the space character (32), are called tokens. Tokens are separated by any number of spaces and control characters (in the range of 0 to 32 decimal). For instance in the following segment,

Writeln('Hello, World!');

there are five tokens: the identifier Writeln, left and right parentheses, the semicolon and the string 'Hello, World!'. Programs are sequences of tokens that tell the compiler what code to generate. There are several different types of tokens; for instance, identifiers, reserved words, operators, and so on. Each type of token is explained further ahead in this manual.

Identifiers are tokens that have a special meaning in TMT Pascal. Identifiers begin with a letter (A-Z or a-z) or underscore, and may contain letters, underscores, and digits (0-9). The maximum length of an identifier is 255 characters, however only the first 63 characters are significant. TMT Pascal is not case sensitive, therefore the identifiers WriteLn, writeln, and WRITELN are all identical. Reserved words, procedure names, and variables, are examples of identifiers.


TMT Pascal Reserved Words
Reserved Words

Reserved words are identifiers with a specific meaning in TMT Pascal. Their meaning can not be changed or altered in any way. The following is a list of TMT Pascal reserved words:

and	end	library	shl
array	exports	mod	shr
asm	file	nil	string
begin	for	not	then
case	function	object	to
const	goto	of	type
constructor	if	or	unit
declare	implementation	packed	until
destructor	in	procedure	uses
div	inherited	program	var
do	inline	record	while
downto	interface	repeat	with
else	label	set	xor

The following table shows TMT Pascal's standard directives. Directives are used only in contexts where user-defined identifiers can't occur. Unlike reserved words, you can redefine standard directives, but we advise that you don't.

__reader	code	index	postlude
__writer	conv	name	private
absolute	export	out	public
assembler	external	overload	stdcall
cdecl	forward	pascal	virtual


Operators and Delimiters

Operators and delimiters are tokens that also have special Pascal meanings. The following is a list of valid operators and delimiters along with their meaning:

token	usage

@	Address operator

^	Pointer dereference operator

+	Addition or set union operator

-	Subtraction or set difference operator

*	Multiplication or set intersection operator

/	Real division

div	Integer Division

mod	Modulus

()	Parentheses

[]	Subscript delimiter, set constants

=	Assignment operator

.	Field selection operator

,	Separator

..	Range separator

:	Type separator or case separator

=	Equal operator

<	Less than operator

>	Greater than operator

<=	Less than or equal operator

>=	Greater than or equal operator

<>	Not equal operator

and	Logical AND

in	Set operator

not	Logical NOT

or	Logical OR

shl	Bit shift left replacing right side with 0's

shr	Bit shift right replacing left side with 0's

xor	Logical XOR

Operator Precedence

Operators allow for the manipulation of certain types of identifiers. For expressions with three or more operands (i.e. 5 *4 + 2), rules of precedence apply. The order of precedence for operators is as follows:

operator                                  type

Unary Operators	@, not

Multiplying Operators	*, / , div, mod, and, shl, shr

Adding Operators	+, -, or, xor

Relational Operators	=, <>, <, >, <{}=, >{}= , in

Operations are performed from left to right while operations of higher precedence are performed first. For more about operators see the chapter on Expressions.


Constants

A constant is an identifier that marks a value that can't change. TMT Pascal provides two standard types of constants:

Integer and Real Number Constants

String Constants

See also:

Constant Declarations


Integer and Real Number Constants

Integer constants are values that can be represented in either decimal (base 10) or hexadecimal (base 16). A decimal number is a string of digits (0-9) that may be preceded with a plus or minus sign. A hexadecimal number is preceded by a dollar sign ($) followed by a string of digits and the characters A through F. The following are valid integer numbers:

   100   -255   100500  $FE   $ABCD

Real constants are numbers that contain an integer portion, a fractional portion, and an exponent. Use real constants when the fraction of a number is necessary. The syntax for real constants is as follows:

  [+|-]  digits [.digits] [E [+|-] digits]

The letter E represents the exponent part of the real number. Exponents are powers of ten. Both integer and real constants may not contain space characters. The following are valid real constants:

1.0   -205.13   9019.31E100   40.71E-10

Important! This version of TMT Pascal compiler does not provide constants of Extended type.


String Constants

String constants are strings of ASCII characters preceded by and followed by a single quote ('). Use two single quotes ('') to represent a single quote within a string. A string may also be constructed with the number symbol # or the caret symbol ^. For more information see the definition of Character types. The maximum size of a string constant is 255 characters. The following are valid examples of string constants:

'This is a string'

^G'A Bell will sound'

#13#11'New Line'

'Where''s the program'


Program Comments

A good programmer knows that comments within a source file can be very helpful. Comments are delimited by “{“ and “}” or “(*” and “*)”. All comments are ignored by TMT Pascal during compilation. Comments cannot contain nested comments that use the same delimiters. Below are examples of traditional Pascal comments:

{ This is a comment }

(* Another comment *)

(* This comment is { nested } *)

{ Another (* nested *) comment }

(* An invalid (* comment *) *)

In addition to traditional comments, TMT Pascal supports C/C++ and Ada-style end-line comments. These begin with a double hyphen and span until the end of the line. For example:

/* This is C-style comment */

Space := ' ';  -- initialize filler char

FillChar(Ptr ($A0000), 64000, 0);  // clear VGA video memory

Remarks:

A comment that contains the dollar sign ($) immediately after opening {, (* or /* is a compiler directive. A mnemonic of the compiler command follows the $ character.

Important! Starting from version 3.0, TMT Pascal is not support Ada-style comments by default. We thinking to completely remove support for Ada-style comments in future and recommend you to replace all Ada-style comments in your programs by traditional Pascal or C/C++ styled comments. Use {$AC+} compiler switch, if you want to compile old sources with TMT Pascal 3.0 or later (see $AC: Ada-Style Comments Switch).


Types

A type defines the kinds and ranges of values that constants, variables, procedures, and functions may contain. Types also define the size of, as well as the operations on such identifiers.

TMT Pascal comes with a powerful set of predefined types and it is possible to define new types for constants and variables.

There are five basic type groups that are available under TMT Pascal. Each group contains types with similar properties. They are the following:

Scalar Types.

Scalar types consist of an ordered set of values. Scalar types include all ordinal types as well as real types. Characters are also of scalar type.

Ordinal Types.

Ordinal types are a subset of scalar types. Ordinal types include boolean, char, enumeration, and integer. Reals are not ordinal types.

Procedure Types.

Procedure types contain the address in memory of a procedure or function.

Pointer Types.

Pointer types store the address of a location in memory. Pointer types can be used to address dynamic variables.

Structured Types.

Structured types are types that contain several components. Each component can be accessed separately or the entire structure can be treated as a whole. Examples of structured types include strings, arrays, records, sets, files, and objects.

Related topics:

Boolean Types

Character Types

Integer Types

Enumeration Types

Subrange Types

Real Types

Pointer Types

Pointer Dereference

Array Types

String Types

Set Types

Record Types

File Types

Procedure Types

Object Types

Structured Types Alignment (packed modifier)

Type Compatibility


Boolean Types

The TMT Pascal compiler has four predefined Boolean types which are Boolean (preferred), ByteBool, WordBool, and LongBool. TheBoolean and ByteBool variables occupy one byte of memory, a WordBool variable occupies two bytes, and a LongBool variable occupies four bytes. Each Boolean type is an ordinal and can hold one of two values: True or False. Expressions that evaluate to a logical "yes" or "no" are of Boolean type. if, while, repeat and other control statements work with Boolean expressions. The following code fragment,

  while not KeyPressed do;

causes program execution to pause until a key is pressed on the keyboard. KeyPressed is a procedure declared in the CRT unit. The expression not KeyPressed results in a Boolean value that determines whether the while loop is executed. not performs a logical NOT on the Boolean returned by KeyPressed. The constants True and False are declared in the System unit as Boolean.

The evaluation model is controlled through the $B compiler directive. The default state is {$B-}, so the compiler generates short-circuit evaluation code. In the {$B+} state, the compiler generates a complete evaluation.


Character Types

Character types require one byte of storage. They may consist of any ASCII character, for instance, 'A' through 'Z', '0' through '9', or any control code. The code fragment below shows various ways to initialize character type variables.

var

  Number, Alpha, Bell, EofMarker: Char;

begin

  Number    := '5';

  Alpha     := 'a';

  Bell      := ^G;

  EofMarker := #27;

end.

A character is normally delimited by two single quotes. However there are two other methods of representing characters as seen in the example above: the caret symbol (^) and the number symbol (#).

Use the caret to represent control codes -- characters between 0 and 31 on the ASCII table. ^G stands for character number 7 because G is the seventh letter of the alphabet. When ^G is used during output the computer's bell will sound.

Use #to represent any ASCII character. As in the example above, the end of file character, which is defined as character number 27 on the ASCII table, is assigned to the variable EofMarker. Note that #27 is the same as ^[.


Integer Types

Integer types may contain both positive and negative integer values. Integer values may range from -2,147,483,648 to 2,147,483,647 and other ranges are alsosupported. Each integer variable requires two bytes of storage. The following is a list of additional predefined integer types.

Integer Types

Type                Range                                                  Format

ShortInt	 	128 .. 127	signed 8-bit

Integer	 	2,147,483,648 .. 2,147,483,647	signed 32-bit

SmallInt	-32,768 .. 32,767	signed 16-bit

LongInt	 	2,147,483,648 .. 2,147,483,647	signed 32-bit

Byte	0 .. 255	unsigned 8-bit

Word	0 .. 65,535	unsigned 16-bit

DWORD	0 .. 4,294,967,295	unsigned 32-bit

LongWord	0 .. 4,294,967,295	unsigned 32-bit

Cardinal	0 .. 4,294,967,295	unsigned 32-bit

On the Intel 386+ CPU's, operations performed with 32-bit integers are faster than operations with 16-bit ones. This is due to the fact that registers on the 32-bit processors are 32 bits wide.


Enumeration Types

Enumeration types are ordinals that represent a set of values specified by a list of identifiers. Enumeration types are defined as follows:

identifier [,identifier]

Each identifier is a constant of the new type. Identifiers in enumeration types are assigned values with the first equal to zero, the second equal to one, and so on. For instance, the following enumeration type contains the seven days of the week:

= (Sun, Mon, Tue, Wed, Thu, Fri, Sat);

In type Week, Sun has the value of zero, Mon has the value of one, Tue has the value of two, and so on.

Enumeration is limited to 256 elements.


Subrange Types

Subrange types restrict the values allowed for a type. The subrange must consist of ordinal type constants and the components of the range must be of the same type. Subranges are defined as follows:

expression .. expression;

where the first expression is the lowest value of the range and the second expression is the highest value. The following are examples of subranges:

type

  Digits = '0'..'9';

  Values = 0..$F;


Real Types

Real data types contain integer values as well as a fractional portion. Also known as floating point numbers, each real type consists of a significant, the fractional part, and an exponent, which is a power of ten.

TMT Pascal follows the IEEE standard for floating point number representation. There are five real data types available under TMT Pascal: Real48, Real, Single, Double, and Extended.

Type                 Range                                                 Format

Single	 	 1.5 x 10E-45 .. 3.4 x 10E38	6 to 7 significant digits, 32-bit

Real48	 2.9 x 10E-39 .. 1.7 x 10E38	11 to 12 significant digits, 48-bit

Double	 5.0 x 10E-324 .. 1.7 x 10E308	15 to 16 significant digits, 64-bit

Real	 5.0 x 10E-324 .. 1.7 x 10E308	15 to 16 significant digits, 64-bit

Extended 	 1.9 x 10E-4951 .. 1.1 x 10E4932	19-20 significant digits, 80-bit

The internal format of TMT Pascal's real type differs to Borland’s one. Actually the generic type Real is equivalent to Double.

Real48 is maintained for backward compatibility with older versions of compiler. Since its storage format is not native to the Intel CPU's, it results in slower performance than other floating-point types.


Pointer Types

Pointer types contain the address of an identifier or dynamically allocated memory. Pointer types require a double word (32 bits for storage). While in protected mode, pointers contain a 32-bit offset and the segment is assumed to be the data segment. In this way pointers are similar to the integer type Longint. To allocate dynamic variables see the chapter on Heap Management. A pointer type must point to specific type. Pointer types are defined as follows:

^Typename

The pointer type can be assigned the constant nil. When nil is assigned, the pointer does not refer to any location in memory. Pointer is a predefined pointer type that is untyped. Pointer is compatible with all other pointer types.

TMT Pascal supports the following arithmetical operations on pointers.

Examples:

p2 := p1 + 1000;

p1 := p2 - $FF;

inc(p1, 15);

dec(p2);

Where p1 and p2 are variables of Pointer Type.


Pointer Dereference

Dereferencing is used to refer to the object which a pointer type points to. Use

Variable^

to dereference a pointer type. It is important to note that pointer types must point to a specific memory location before they are dereferenced. Otherwise, the data pointed to is undefined.


Array Types

array types contain a sequence of components of a different type. Each component is referenced by an index which also has a specific type. Arrays are defined as follows:

array [Ordinalindex [,OrdinalIndex]] of Arraytype;

where OrdinalIndex is one of the following ordinal types: integer, char, enumeration, boolean, or subrange. Arraytype can be of any type, including another array type. The following are examples of array types:

array [Boolean] of Char;

array [Char] of Integer;

array [1..255] of Double;

Subscripts are used to refer to a component of an array. Subscripting an array is specified as follows:

Arrayname [expression [,expression]];

where expression is of the same type as the index. Expression must also lie within the range of the index. A runtime error is generated if expression lies outside the index range and range checking is turned on, $R+.


String Types

Strings are arrays of characters. The maximum size of a string type is 255 characters. In the following example two string variables are declared, one with a specific size, the other with the maximum size of 255 characters.

S1: String[100];

S2: String;

The variable S1 holds only the first 100 characters of a string. S2 may contain up to 255 characters. TMT Pascal reserves one byte, which contains the size of the string. This size byte is reserved in the byte that precedes the first character of a string. For instance,

S2 := 'Hello World';

is represented in memory as

#11,Hello World

All string operations, as well as functions and procedures that return or modify strings, truncate strings that exceed 255 characters.


Set Types

Set types specify a subset of a set of values. The ordinal value of the set elements must range between 0 and 255.

- Characters

- Enumeration type

- Positive integer values

- Subrange of the above three

- Ordinal types

Each value in a set is defined by one bit, therefore each value is similar to a Boolean. The following are examples of sets:

type

  set of 0..7;

  set of '0'..'9';

  set of Char;

  set of Word;  - This cannot be handled by BP.


Record Types

Record types are structures that contain components of different types. Each component of a record is called a field. Variant sections are parts of records can have multiple definitions. Record type are defined as follows:

record

  Fieldlist

end

where Fieldlist is defined as:

[[Fixedpart] | [Fixedpart;] [Variantpart]];

where Fixedpart is:

Field [; Field];

where Field is

identifier [,identifier] : Identifiertype;

Variantpart is defined as follows:

case

  [identifier:] Typename of Variant [;Variant];

where Variant is:

Caserange [,Caserange] : (Fieldlist);

where Caserange is:

expression [..expression];

With a proper understanding of TMT Pascal record types, very powerful types can be defined. The following are examples of record types:

type

  Coordinate = record

    x,y   : Integer;

  end;

  Values = record

    case Way : Boolean of

      True  : (RValue : Extended);

      False : (IValue : Longint);

    end;

To reference a field of a record specify the record variable followed by a period (.) followed by the field name. The following refers to the fields of Coordinate declared above:

Coordinate.x

Coordinate.y


File Types

File types are structures that contain components of any type except another file type. File types are defined as follows:

File [of Componenttype];

If of is not specified and component types are not indicated then the file is untyped. Untyped files are used to access files regardless of their structure. Text file types refer to a file of ASCII characters grouped in lines. Text is a predefined type.

The record definitions used internally by TMT Pascal are also declared in the System unit.

TFileRec is used for both typed and untyped files.

type TFileRec = object

  magic   : ^TFileRec;

  name    : string;

  handle  : Longint;

  rec_len : Longint;

  state   : %flags;

  rd_proc,

  wr_proc : function (F: Longint; Buf: Pointer; Len: Longint; var Act: Longint): Longint;

  procedure check_magic;

  procedure check_opened;

  procedure check_readable;

  procedure check_writeable;

  procedure io_error(code: Integer);

end;

PFileRec = ^TFileRec;

TTextRec is the internal format of a variable of type text.

type TTextRec = object(TFileRec)

  buffer  : array [0..63] of Char;

  index   : Longint;

  len_buf : Longint;

  max_buf : Longint;

  buf_adr : Pointer;

  function  Eof: Boolean;

  procedure init;

  procedure fill_buf;

  procedure fill_chr;

  procedure skip_spaces;

  procedure get_n_char(n: Integer);

end;

PTextRec = ^TTextRec;

Internal Type %flags is declared as:

type %flags = set of %file_state;

where %file_state is:

type %file_state =

(

    %file_readable,  //00h

    %file_writeable, //01h

    %file_opened,    //02h

    %file_assigned,  //03h

    %file_eof,       //04h

    %file_text,      //05h

    %file_file,      //06h

    %file_fileof,    //07h

    %file_tty,       //08h

    %file_special,   //09h

    %file_settextbuf //0Ah

);


Procedure Types

Procedure types contain the address of a procedure or function. Procedure types are followed by blocks of data and code and are defined as follows:

procedure identifier [(Parameterlist)]}

or

function identifier [(ParameterList)] : ReturnType}

ReturnType is the type of value returned by the function. ParameterList is defined as:

Parameter [;Parameter]}

where Parameter is:

[var] identifier [,identifier] : Typename}

var specifies a variable parameter. var parameters are passed by reference as opposed to being passed by value. The following are examples of procedure types:

procedure PrintAt(X, Y: Integer; S: String);

function  Max(Value1, Value2: Integer) : Integer;

procedure GetDir(Driver: Byte; var S: String);

Important! Note that unlike pointers, procedure types occupy 8 bytes. Besides the address of the procedure proper, the local frame is stored. This allows the forming of procedure types out of local procedures.


Object Types

Object types are similar to the record types in containing components of different types. However, unlike records, objects may contain methods and be inherited. The full description of object types can be found elsewhere (see the OOP Extensions chapter.)


Structured Types Alignment (packed modifier)

By default, the data in a structured type is aligned on double-word boundaries for faster access. However it's possible to include the reserved word packed to enable data compression. For example,

type

  TEmployee: = packed record

    name: String[80];

    appointment_id: Word;

    stage: Byte;

end;

The setting defined by the {$OA} directive can be overridden by specifying the packed reserved word.


Type Compatibility

There are three levels of type compatibility. Each level along with its restrictions is listed below in order, from the most restrictive to the least restrictive.

Equivalent Types.

Two types are equivalent only if they are both defined from the same type declaration. That declaration must be one if the following:

- A named type declared by a type declaration.

- A predeclared type.

- An unnamed type used in a declaration.

Compatible Types.

Two types are compatible if one of the following apply:

- Both are equivalent.

- One type is a subrange of another.

- Both are subranges of the same type.

- Both types are integers.

- Both types are reals.

- Both types are strings.

- One is a char or array of char and the other is a string.

- Both are set types and their base types are compatible.

- Both are arrays of char with the same length.

Assignable Types.

A type is assignable to another type if one of the following apply:

- Both types are compatible.

- Assignment of an integer type to a real type.

- Assignment of a char type to a string type.

- An array of characters less than 256 characters to a string.

- Both procedure types have the same parameters.


Declarations

The name of each identifier must be declared in your source code. By declaring an identifier to be of a particular type, such as a variable, or constant, you define its size and attributes.

Pascal is a block structured language. Each program, unit, procedure and function defines a block. Blocks can be nested creating blocks within blocks. The block structure effects the interpretation of identifiers such as constants, variables, types, and so on. Identifiers can have different meanings depending upon which block is referenced.

When an identifier is declared it is defined from the point of its declaration to the end of the inner most block that contains the declaration. This is the scope of the identifier. Redefinition of an identifier is not allowed within the same block in which it was declared. Only in nested blocks may an identifier be redefined. However the new identifier does not refer to the old identifier. In fact the old identifier is hidden until the end of the nested block.

In addition to the traditional Pascal syntax, TMT Pascal also allows local block declarations. These are described below in the manual.

An identifier may not be referenced prior to its declaration with one exception. A type name can be used as the base type of a pointer if the name is then declared in the type declaration that contains the reference. For instance:

type

   CoordPtr   = ^Coordinate;

   Coordinate = record;

     x, y     : Integer;

   end;

As you can see Coordinate is referenced prior to its declaration. The above declaration is valid due to the fact that Coordinate is declared in the same type declaration as CoordPtr.

There are several declarations possible under TMT Pascal. They include:

Type Declarations

Label Declarations

Constant Declarations

Variable Declarations

Local Block Declarations


Type Declarations

Type declarations are preceded by the type reserved word.

type identifier = Identifiertype;

Identifier is the actual name of the new type you define. Identifiertype is the type of identifier. Identifiertype can be on of the following:

Another Type     String        Pointer      File

Subrange         array         set          function

Enumeration      record        procedure    Text

Some examples of type declarations are:

type

  Float        = Extended;

  Int          = Integer;

  Filename     = array [0..8] of Char;

  Fnameptr     = ^Filename;

  Seasons      = (Winter, Spring, Summer, Autumn);


Label Declarations

TMT Pascal statements may be labeled with one of two types of labels. A label can either be a positive integer number (0...2147483647) or an identifier. Before using labels in your code, a label must be declared. A label declaration is preceded by the label reserved word.

label identifier [,identifier];


Constant Declarations

There are two types of constants and TMT Pascal interprets them both differently.

Constants that are declared without a type may not be changed in the program. Constants that are typed are the same as variables (described below), however they contain an initial value. These constants may be changed in the program. A constant declaration is preceded by the const reserved word.

const identifier [:IdentifierType] = expression;

Identifier is the actual name of the constant defined. IdentifierType, which is optional, specifies the type of the constant. Again, if a type is specified, the constant is the same as a variable with an initial value. Expression is assigned to the constant and must be evaluated at compile time. The following are untyped constants and may not be modified:

const

  Digit   = '0'..'9';

  MaxSize = 100;

  Msg     = 'This is a string constant';

Typed constants may be of any type except for file, procedure, or function. Some examples of typed constants are:

type

  Coordinate = record

    x,y      : Integer;

  end;

const

  Originpos : Coordinate = (x:0; y:0);

  Name      : String = 'Hello World!';

  StrSize   : Integer = 100;

  Ary       : array[False..True] of Byte = (10,15);

See also:

Integer and Real Number Constants

String Constants


Variable Declarations

Variables store data during program execution. A variable declaration is preceded by the var word.

var identifier [,identifier]: IdentifierType;

Identifier is the actual name of the variable defined. IdentifierType specifies the type of the variable. Variables, unlike constants, are not initialized. Their content prior to initialization is undefined. It is also possible to specify the absolute address of a variable. Following the Identifiertype specify the absolute reserved word.

var

  identifier [,identifier]: IdentifierType absolute address;

Address may be either an identifier or an integer number indicating an offset. If Address is an identifier then TMT Pascal computes it's offset. absolute mapsthe variable to the address following the absolute statement. This identifier must be declared prior to using absolute. If a variable is the absolute of another, both address the same data however the types may be different. The following are examples of variable declarations.

const

  BuffSize = 921600;  // 900K

var

  HugeBuff : array [0..BuffSize] of Char;

  i,j,k,l  : Integer;

  Buffptr  : Longint;

  p        : Pointer absolute Buffptr;

  Alpha    : Char;}

The absolute may refer to fields of records and objects. Also, the address of a global record/object field can be used within the initialization of typed constants. Furthermore one can use recursive initialization:

type rec = record

  next:    ^rec;

  buffer:  array [1..10] of char;

  buf_adr: pointer;

end;

const cyclic: rec = (next: @cyclic; buf_adr: @cyclic.buffer);

The TMT Pascal compiler allows one to specify the out parameter to specify an argument of a function or procedure. It has a similar purpose to a variable parameter, since it is also passed by reference. However the out parameter is intended for output only (it tells the function or procedure where to store output, but doesn’t provide any input).

For example,

procedure GetCoord(out x, y: Integer);

The procedure above returns two integer values: x and y.


Local Block Declarations

It is very often necessary to declare a local variable with a short life-span. One has to do this at the declaration part of a program or in the procedure body. This is not always convenient, especially if there is a huge program with a complicated algorithm. For that case a special construction has been added in TMT Pascal. It is called a Local or Nested Block. Such a block is an ordinary compound statement which begins with the new reserved word 'declare' and consists of two parts---declaration and execution:

declare

  <declaration part>

begin

  <execution part>

end;

This statement can be used in any place where a structured statement can be placed.

Example:

program DeclDemo;

{$ifndef __CON__}

  This program must be compiled for MS-DOS, OS/2 or Win32 console mode

{$endif}

var

  b: Integer;

begin

  declare  // first local block

    var

      a: Integer;

    procedure pr_int (a: Integer);

     var

       i: Integer;

     begin

       for i := 1 to a do

       declare  //second local block

       var

         k: Integer;

       begin

         k := a div i;

         Writeln (a, ' div ', i, ' =  ', k);

       end;

     end;

  begin

     a := 1;

     Writeln (a);

     b := 10;

     pr_int (b);

  end

end.

This example contains two local blocks one of them is in the program body and another is in the routine body. The first local block declares variable a and procedure pr_int, the second declares one local variable k. It should be understood that the scope of 'a' and pr_int is the interior of the "first local block," and the scope of k is the interior of the "second local block."


Expressions Declarations
Expressions

Expressions are constructs made up of operators and operands. Expressions work with existing data and return new data. In TMT Pascal there exist two types of operations, unary and binary. Unary operations work with one operand and binary operations work with two operands. Regardless of the operator, operands may be constants, variables, data returned by another operator, or data returned by a function call. Operators can be grouped according to the types they operate on. There are five groups of operators: integer, real, boolean, set, and relational.

Here is a description of the operator groups:

Arithmetic Operators

Boolean Operators

Set Operators

Relational Operators

Tpyecasts

Operator Precedence


Arithmetic Operators

Standard arithmetic operators listed below.

Operator      Operation

 @            Pointer formation

 +            Unary sign identity

 -            Unary sign negation

 +            Addition

 -            Subtraction

 *            Multiplication

 Div          Integer division

 /            Real division

 Mod          Integer remainder

 And          Logical AND

 Xor          Logical XOR

 Not          Logical NOT

 Or           Logical OR

 Shl          Shift bits left

 Shr          Shift bits right

During binary operations both operands must be of compatible type. If the operands are of compatible type then the operation results in the same type of the operand. If the types are different then the result is the larger type.

For integer operations, operands are converted to Longint and results are of the same type as the destination type. Longint or 32 bit operations are faster on the 80386 and 80486.

During real operations, operands are converted to extended type and results are of the same type as the destination.


Boolean Operators

Boolean operators include logical AND, NOT, OR, and XOR. The operation of each is summarized below:

Operator     Logical Operation

 AND         Conjunction

 NOT         Negation

 OR          Disjunction

 XOR         Exclusive Disjunction

Boolean expressions that evaluate to True return a value of one. Boolean expressions that are False result in a zero value.


Set Operators

Set operators are defined as follows:

Operator   Meaning       Operation

    +      Union         Yields elements in either A or B

    -      Difference    Yields elements in A but not in B

    *      Intersection  Yields elements in both A and B


Relational Operators

Relational operators perform arithmetic, literal, and set comparisons. All relational operations result in a Boolean type. Relational operators

include:

Operator  Meaning                Applicable types

 =        Equal                  integers, reals, booleans,

                                 chars, enumerations, strings,

                                 sets, pointers

 <        Less than              integers, reals, boolean,

                                 char, enumerations, strings,

                                 pointers

 >        Greater than           integers, reals, boolean,

                                 chars, enumerations, strings,

                                 pointers

 <=       Less than or equal,    integers, reals, booleans,

          set inclusion          chars, enumerations, strings,

                                 pointers

 >=       Greater than or equal, integers, reals, booleans,

          set inclusion          chars, enumerations, strings,

                                 pointers

 <>       Not equal              integers, reals, booleans,

                                 chars, enumerations, strings,

                                 sets, pointers

 In       Membership             A set type on the right and

                                 the set's base type on the left


Typecasts
Tpyecasts

Typecasts allow operands of one type to be converted to another type. Typecasts are allowed on either values or variables. Typecasts on values are restricted to ordinal and pointer types. The only restriction on typecasts on variables is that the sizes of both types must be the same. The following are examples of typecasts.

Integer('0')

Boolean(1)

Wordptr(@BuffPtr)

Char(27)

Longint(@BuffPtr)}


Operator Precedence

For expressions with three or more operands (i.e. 2 - 244 / 4), rules of precedence apply. The order of precedence for operators is listed from highest to lowest:

Operator Type             Operator

Unary Operators           @,Not

Multiplying Operators     *,/,Div,Mod,And,Shl,Shr

Adding Operators          +,-,Or,Xor

Relational Operators      =,<>,<,>,<=,>=,In

Operations are performed from left to right while operations of higher precedence are performed first. For instance, the following expression:

 7 + 4 * 2

is not the same as:

  (7 + 4) * 2

Since multiplication has a higher precedence than addition, multiplication is performed first followed by addition. Use parenthesis to separate operations that you want to be performed first.


Stetements
Statements

A statement indicates the action a program performs. Statements are separated by semicolons (;). Statements may be preceded by a label which consists either of an identifier or an unsigned integer constant.

Assigments

Compound Statements

Case Statement

For Statement

Goto Statement

If Statement

InLine Statement

Repeat Statement

While Statement

With Statement

Mem, MemW, MemL, and MemD

Port, PortW and PortD


Assigments

An assignment assigns a value to a variable. An assignment takes the following form:

 variable := expression;

where the value returned by expression is stored in variable. The type of the value returned by expression must be compatible with the type of variable. If variable appears in expression, its value is the value prior to the assignment. The following are examples of assignments:

const

  Letter    = 'A';

var

  Alpha     : Char;

  Value, i  : Integer;

  l         : Longint;

  s         : String;

begin

  Alpha     := Letter;

  s         := 'A string variable';

  Value     := $643F;

  i         := 2675;

  l         := 200 + (Value * i);

end.


Compound Statements

Compound statements are comprised of single statements preceded by begin and followed by end. Compound statements take the following form:

begin

  [statement [; statement]]

end

Compound statements allow one to place two or more statements wherever a statement is called for within another statement.


Case Statement

The case statement selects from a list of statements basing it's decision on the value of an expression. case statements take the following form:

case expression of

  Selector : statement

  [else statement]

end;

where expression is a value of ordinal type. The case expression value is matched against each Selector. If a match exists the statement following the matching Selector is executed. Control is then transferred out of the case. If no Selector matches the case expression then control is passed to an optional else clause. Selector must evaluate to a constant at compile time and is defined as:

expression [..expression] [,expression [..expression]]}

if .. is specified followed by another expression the case applies to the entire range between the first expression and the second expression. The following is an example of the case statement:

case Int of

  5         : WriteLn('Int is 5');

  7..12,15  : WriteLn('Between 7..12 or 15');

  else        begin

                WriteLn('Undefined.');

                GetNextInt;

              end;

end;

Performance for large case statements improves if the most common subcases are listed first.


For Statement

The for statement allows for repetitive execution of one or more statements. for executes a loop for a predetermined number of iterations. for statements take the following form:

for variable := expression to | downto expression

  do statement

where variable must be of ordinal type. The first expression following variable is the initial value that is assigned to variable and the second expression is the limit on the range of values assigned to variable. Both expressions must be of compatible type.

The to or downto clause specify specifies whether a variable is incremented or decremented after each iteration of the loop. If to is specified, the variable is incremented until it hits the limit of the second expression. downto decrements variable until it reaches the lower limit of the second expression.

The following are examples of for loops:

for i := 1 to 100 fo

begin

  WriteLn(i);

  Intarray[i] := i + 4;

end;

for x := 5 downto 2 do

  WriteLn(x);

A for loop is not executed if the first expression is greater than or less then the second expression depending upon whether a to or downto was specified. For instance the following for loop is not executed:

for i := 5 to 4 do

  WriteLn('Will never output this string!');

For a loop, the index variable must either be global or local to the procedure to which it belongs.


Goto Statement

As mentioned above statements may be preceded by labels. The goto statement

transfers control to a specific label. The format of a goto statement is as

follows:

goto label;

where label has been previously declared in the current block. The following is an example of the goto statement:

label

  GotoLoop;

var

  i: Integer;

begin

  i := 1;

GotoLoop:

  WriteLn(i);

  Inc(i,2);

  if i < 100 then

    goto GotoLoop;

end.


If Statement

The If statement conditionally executes one of two statements based on the value of an expression. If statements take the following form:

if expression then

  statement

[else statement]

where expression evaluates to a boolean value. If expression results in True then the statement following the reserved word then is executed. Control is then transferred to the first statement outside the if statement.

If expression evaluates to False and an else clause is specified then the statement following else is executed. If no else clause exists and expression is False then the if statement is passed over. The following is an example of an if statement.

if Flag then

  WriteLn('Expression is True')

else

  WriteLn('Expression is False');

The end of an if statement is indicated by a semicolon (;). In the above example, if Flag is a constant then TMT Pascal optimizes code generation and automatically eliminates code that is never executed.


InLine Statement

The inline clause is used to define a short machine language routine. inline procedures are treated as macros rather than procedure calls and are therefore extremely efficient. It is recommended that you have thorough knowledge of 32 bit assembler before writing machine code macros.

function IsLower(Ch:Char):Boolean;

  inline(

         $58/           {  pop     eax    }

         $3C/$61/       {  cmp     al,'a' }

         $0F/$90/$C4/   {  setge   ah     }

         $3C/$7A/       {  cmp     al,'z' }

         $0F/$9E/$C0/   {  setle   al     }

         $22/$E0)       {  and     al,ah  }

Notice the use of new 80386 and 80486 instructions. For more information about 386 and 486 extensions refer to your Intel™ reference manual.


Repeat Statement

The repeat statement, much like the for statement, executes one or more statements in a loop. Unlike a for statement where the loop condition is tested prior to each iteration, a repeat statement condition is tested after each iteration. Therefore a repeat loop is executed at least once. repeat takes the following form:

  repeat

    statement [; statement]

  until expression;

where the repeat loop executes until the expression evaluates to the boolean value of True. When the expression is False, the loop is executed again. The following is an example of the repeat statement:

  repeat {Do nothing} until KeyPressed;


While Statement

The While statement executes one or more statements in a loop. while statements take the following form:

  while expression do

    statement

where expression evaluates to a Boolean type. A while loop executes until expression evaluates to False. when False, control is transferred to the first statement outside the while loop.


With Statement

The with statement allows one to refer to the fields of a record type as if they were independent variables. with takes the following form:

with variable [, variable] do

  statement

where variable refers to a record type. Statement may refer to the fields of variable without specifying the variable name. The following is an example of the with statement:

type

  ScreenString = record

  x,y          : Integer;

  str          : String;

end;

var

  ScrnSay : ScreenString;

begin

  with ScrnSay do

  begin

      x    := 5;

      x    := 5;

      y    := 10;

      str  := 'Hello World!';

  end;

end.


Mem, MemW, MemL, and MemD

TMT Pascal implements four predefined arrays to directly access memory:

Mem, MemW, MemL, and MemD.

•	Each component of Mem is a Byte

•	Each component of MemW is a Word

•	Each component of MemL is a Longint.

•	Each component of MemD is a DWORD.

See also:

Memory Organization


Port, PortW, and PortD
Port, PortW and PortD

TMT Pascal implements three predefined arrays to directly access 80x86 CPU data ports:

Port, PortW, and PortD.

Port, PortW, and PortD are one-dimensional arrays, and each element represents a data port whose port address corresponds to its index.

•	Each component of Port is a Byte

•	Each component of PortW is a Word

•	Each component of PortD is a DWORD.

When a value is assigned to a component of Port, PortW or PortD, the value is output to the selected port. When a component of Port, PortW or PortD is referenced in an expression, its value is input from the selected port.


Programs and Units

TMT Pascal source files contain units, programs, or both. A unit is a collection of procedures, functions, and data that is accessible to other programs or units. Units aid in the modular design of applications and are similar to libraries. Units may not be executed directly. A program consists of one or more procedures or functions. The main procedure of a program is executed during runtime.

Units

Programs


Units

Units can be compiled separately and take the following form:

unit Unitname;

interface

  [Declaration]

implementation

  [Declaration]

[

  begin

  [statement [; statement]]

]

end.

Unitname is the name of the unit. This is the same name that you will use in programs to reference the unit. There are three sections within each unit.

Interface Section

The Interface section contains declarations of types, constants, variables, procedures, and functions that are public and accessible to other programs and units. When declaring procedures and functions in the Interface section, only the procedure header is required. These declarations are similar to using the Forward clause that tells TMT Pascal that the complete declaration is further ahead in the program. The entire procedure declaration is done in the Implementation section. Local variables and procedures that need not be accessible outside of the unit may be declared in the Implementation section.

Implementation Section

The Implementation section contains local types, constants, variables, labels, procedures and functions. Procedures and functions are local to the unit unless their header is also declared in the Interface section. The Implementation section contains complete procedure and function declarations.

Unit Initialization

The initialization section starts immediately after the Begin statement. This code block is executed by the main program that uses the unit. It is executed prior to the main code block.

Each unit is terminated by the End statement followed by a period. The reserved words Interface and Implementation must be specified in a unit. The initialization section is optional.

In Borland Pascal, private procedures are compiled as near while public procedures are far. Therefore private procedures are more efficient. In TMT Pascal both private and public procedures are near and equally efficient.


Programs

Programs require a different format from units. The general format takes the following form:

[program identifier;]

[uses Unitname [, Unitname]]

[Declaration]

begin

  statement [; statement]

end.

The identifier following the program statement declares the name of the program. Program files are terminated by the end statement followed by a period “.”.

The uses statement tells TMT Pascal which units it uses. Unitnames listed after the uses statement are loaded by TMT Pascal. Procedures and variables referenced by the program are linked into the executable generated. All types, constants, variables, and functions declared in the Interface section of units are accessible to the program.

All text beyond the final end statement in either a unit or program is ignored by TMT Pascal.

New feature! In TMT Pascal the main program may contain interface and implementation parts. This allows access to the variables of the main program from other modules:

// Test program

program Test;

interface

  var global: Integer;

implementation

uses UnitTest;

begin

  UnitTest.Write;

end.

// Test unit

unit UnitTest;

interface

  procedure Write_global;

implementation

uses Test;

  procedure Write_global;

  begin

    Write(test.global);

  end;

end.

Important! Here the name of the file that contains the text of the main program or unit must be identical with the name that follows the keyword Program.


Procedures and Functions

Procedures are a sequence of instructions that are separate from the main code block. Functions are procedures that return a value. Other than this difference, both procedures and functions are the same.

Procedures are blocks of code that are called from one or more places throughout your program. Procedures make source code more readable and reduce the size of the executable because repetitive blocks of code are replaced with a call to a procedure. Both procedures and functions accept parameters. Parameters allow the calling routine to communicate with a procedure.

Parameters can be passed by value or by reference or by constant reference.

If passed by value, only the value of the parameter is passed and the procedure has no access to the actual variable. One can modify the value parameter. It will have an effect only inside of the procedure body and will not change the actual variable.

If passed by reference, also known as Var parameters, an address of the memory location containing the value is passed thus making it possible to modify the variable.

If passed by constant reference, also known as Const parameters, an address of the memory location containing the value is passed but the compiler does not allow one to modify a constant parameter and does not allow passing one as an actual variable parameter to another procedure or function.

Procedures and Functions Declaration

Forward Declaration

External Declaration

Interrupt Procedure

Procedural Value

Using Statement as Procedure


Procedures and Functions Declaration

Procedures and functions take the following form:

procedure identifier [(Parameterlist)]}

or

function identifier [(Parameterlist)] : ReturnType}

ReturnType is the type of the value returned by the function. Parameterlist is defined as:

Parameter [;Parameter]}

where Parameter is:

[var] identifier [,identifier] [: TypeName]}

or

[const] identifier [,identifier] [: TypeName]}

var specifies a variable parameter. const specifies a constant parameters. var and const parameters are passed by reference as opposed to being passed var and const parameters are passed by reference as opposed to being passed by value.

The body of a procedure or function takes the following form:

[Declarations]

begin

  statement [; statement]

end;

Types, labels, constants, and variables declared in the declaration section prior to the begin statement are local variables. Space for these variables is allocated only when the procedure is called. Like all variable declarations their data is undefined until initialized. TMT Pascal procedures and functions may be called recursively.

All identifiers must be declared prior to being referenced. The same rule applies to procedures and functions.


Forward Declaration

The forward clause is used to define a procedure prior to its complete declaration. forward tells TMT Pascal that the declaration is further ahead in the program. A forward procedure declaration takes the following form:

Procedureheader; forward;


External Declaration

The External clause is used to define a procedure that is linked in from an assembly object.

Example:

;----------------- [vga.asm] ----------------

IDEAL

P386

MODEL FLAT,PASCAL

CODESEG

GLOBAL  SETVIDEOMODE: PROC

PROC    SETVIDEOMODE USES EAX, MODE: WORD

        MOV     AX,  [MODE]

        INT     10H

        RET

ENDP    SETVIDEOMODE

GLOBAL  CLEARVGA: PROC

PROC    CLEARVGA  USES ECX, COLOR: BYTE

        MOV     EDI, 0A0000H

        MOV     AL,  [COLOR]

        MOV     AH,  AL

        MOV     ECX, EAX

        SHL     EAX, 16

        MOV     AX, CX

        MOV     ECX, 64000/4

        CLD

        REP     STOSD

        RET

ENDP    CLEARVGA

END

;--------------------------------------------

///////////////// [Test.pas] ////////////////

program Test;

{$ifndef __DOS__}

  This program must be compiled for MSDOS target only

{$endif}

uses CRT;

{$l vga}             // include vga.obj file

procedure SetVideoMode(Mode: Word); external;

procedure ClearVGA(Color: Byte); external;

begin

  SetVideoMode($13); // setup VGA/MCGA mode 320x200

  ClearVGA(10);	   // fill screen with green color

  ReadKey;	   // wait for key hit

  ClearVGA(15);	   // fill screen with white color

  ReadKey;	   // wait for key hit

  ClearVGA(0);	   // fill screen with black color

  ReadKey;	   // wait for key hit

  SetVideoMode($03); // setup VGA text mode 80x25

end.

/////////////////////////////////////////////

See also:

Dynamic-Link Libraries (DLL’s)


Interrupt Procedure

In TMT Pascal, the Interrupt clause defines a procedure that is to be used as an interrupt handler.

The parameters of an interrupt procedure are the CPU registers. The following is the order of the CPU registers: EFLAGS, CS, EIP, EAX, EBX, ECX, EDX, ESI, EDI, DS, ES, EBP. If these register variables are assigned a new value, upon completion of the interrupt the new values will be restored onto the actual CPU registers.

Declaration:

procedure IntProc(used registers); interrupt;

An example below shows you a simple method of working with interrupt-handlers.

program Timer1;

uses Dos, Crt;

var

  Int1CSave: FarPointer;

  Time: LongInt;

// TimerHandler

procedure TimerHandler; Interrupt;

var

  StoreX, StoreY: Word;

begin

  Inc(time);

  StoreX:= WhereX;

  StoreY:= WhereY;

  GotoXY(1,1);

  Write(time);

  GotoXY(StoreX, StoreY);

  Port[$20] := $20;

end;

begin

  ClrScr;

  Time := 0;

  GetIntVec($1C, Int1CSave);

  SetIntVec($1C, @TimerHandler);

  Writeln;

  Writeln('Type something and press "ENTER" to exit');

  Readln;

  SetIntVec($1C, Int1CSave);

end.

Important! When using Intr() and MsDos(), keep in mind that the DOS interrupt handlers can deal only with the addresses from the 1st megabyte of memory.


Procedural Value

TMT Pascal has a notion of a procedural value. It gives an opportunity to use procedure or function in a program as a usual simple type object such as enumerate type or subrange type. One can declare an variable of the procedural type, make an assignment to it, and invoke the procedure body from.

By default the procedural value implemented in the TMT Pascal occupies 4 bytes of memory.

It's also possible to declare the extended ("old-style") procedural values by means of arg_proc_based calling convention modifier. These procedural values which occupy 8 bytes of memory and consist of two parts: the entry point to the routine and the reference to the local environment of the routine (known as a routine base). A format of the extended procedural value is following:

The first part is needed for calling of the routine. The second part is used to access the routine variables. Such format of the procedural value is incompatible with the Borland Pascal format which has only the entry point.

Furthermore, the stack frame structure and parameter passing conventions differ from those in Borland Pascal.

Thus the approach used in TVision and CLassLib for writing iterations cannot be used. However, we offer this correct and reliable (and more standard) way:

type list = object

  next: ^list;

  procedure for_all(procedure body(var v));

end;

procedure list.for_all;

var

  p: ^list;

begin

  p := @self;

  repeat

    body(p);

    p := p^.next;

  end;

end;

...

type int_list = object(list)

  value: integer;

  function first_positive: ^int_list;

end;

function int_list.first_positive;

label OK;

var

  res: ^int_list;

procedure do_item(var v);

begin

  if int_list (v).value > 0 then

  begin

    res := @v;

    goto OK;

  end

end;

begin

  res := nil;

  for_all(do_item);

OK:

  first_positive := res;

end;

...

The procedural value from a method of object can be obtained by selecting this method from some object value (not from a type). The parameters of this procedural value must match the parameters of the method. The invocation of such a procedural value is an invocation of the corresponding method of the object. The reference to the object is transferred through the base of the procedural value.

You can use only global procedural values to initialize a type constant.

Procedural values may be used only while the environment where they were formed is still in existence. Thus,

−	for local procedures -- until the exit from the block, in which they are described;

−	for methods -- while the underlying object still exists.


Using Statement as Procedure

With TMT Pascal you can use any statement as a procedure body, except for the assignment and the procedure calls.

The RESULT variable in the body of such functions denotes the variable that contains the return value. The RESULT is of the function return type and may be used as a variable without any restrictions.

With TMT Pascal you can enter the procedure body directly as a procedure parameter. The procedure or function header (if not specified) takes the procedural parameter type. If the procedure header is specified, the procedure name is omitted.

Example:

function Integral(function f(a: Real):Real; low, high, step: Real): Real;

begin ... end;

...

Writeln(integral (

  function(x: Real): Real; begin Result := sqrt(x) end, 0, 10, 0.1));

Writeln(integral(begin Result := sqrt(a) end, 0, 10, 0.1));

Writeln(integral(

                 function;        // function keyword needed

                 var x: Real;     // for local declaration

                 begin x := sqrt(a); Result := x end, 0, 10, 0.1)

                );

Writeln(integral(

                  declare;        // other way

                    var x: Real;  // for local variable declaration

                  begin

                    x := sqrt(a);

                    Result := x

                  end, 0, 10, 0.1)

                 );

TMT Pascal allows exit from a local procedure to the one that contains it. This feature is listed in the Pascal's ANSI standard but not realized in Borland Pascal. Together with procedural values, this is very useful for error handling:

program Test;

var

  on_eof: procedure;

  function read_char: char;

var c: char;

begin

  if Eof (Input) then on_eof;

  Read(c);

  Read_char := c;

tnd;

procedure MyProc;

label eof_reached;

  procedure go_eof;

  begin

    goto eof_reached;

  end;

  begin

    on_eof := go_eof;

    while True do Write (read_char);

    Eof_reached:

    writeln ('*** EOF ***');

    on_eof := nil;

  end;

begin

    MyProc;

end.

Restriction. Break and Continue operators cannot be used for exit from a procedure. Use Goto instead.

Example:

{ incorrect example }

for i := 1 to 10 do

Writeln (

  integral(            // from previous example

           if a < 0

           then break  // incorrect

           else result := sqrt (a),

           i, i + 1, 0.01)

          );

{ correct example }

declare

  label L;

begin

  for i := 1 to 10 do Writeln (

  integral(

           if a < 0

           then goto L  // correct

           else result := sqrt (a), i, i + 1, 0.01)

          );

Functions may return any values of any type, including structures and arrays.


OOP Extensions

TMT Pascal implements object oriented programming (OOP) extensions similar to the OOP extensions in Borland Pascal. This sections describes the applicable syntax of OOP.

Object

Inheritance

Object Syntax

Restrictions On Object Description

OOP Scopes

Public and Private declarations

Virtual Methods

Constructors

Fail procedure

Using New Procedure (OOP)

Desctructors

Inherited reserved word

Self argument


Object

An object is a structure that consists of fields and methods. The fields are effectively declarations of data while the methods define routines that act on the data. Object types allow four types of routines: procedures, functions, and also constructors and destructors; the latter two are allowed only within objects.

See also:

Object Syntax


Inheritance

One object type can extend another object type by adding or replacing fields and methods. In this case the new object is said to be a descendant object; the older object is said to be an ancestor object. The process of an extension is called its inheritance. The descendant object type may have its own descendants; these are also viewed as the descendants of the original ancestor object. The domain of an object, is the object together with all of its descendants.


Object Syntax

The syntax of an object type declaration is

object [heritage]

  Component list

  [ private Component list ]

end

where Component list is defined as:

  [Fieldlist]

  [Method list]

Heritage:

  (object type identifier)

Fieldlist:

  [ field entry [; Field list ] ]

Field entry:

  identifier list : type

MethodList:

  [ method entry [; MethodList ] ]

Method entry:

  [ method heading [; virtual ] ]


Restrictions On Object Description

Object types can be declared everywhere a type identifier is allowed by Pascal's syntax. Object types can be declared within procedures, functions, or other methods if the declaration is not ambiguous.

Like records, object types cannot include File components or records or objects that include 'file' components.


OOP Scopes

Component identifiers are visible in all the methods throughout the domain of the object, including the procedures, functions, destructors and constructors that implement the methods of the object type and its descendants. However, the scopes of the fields and methods declared in the private section of the object type declaration are restricted to the unit that contains the definition of the object type. Private fields and methods are inaccessible from other units. Private fields and methods can, however, be accessed from other object types declared in the same unit. Below are examples of several objects:

type Point =

  record

    X,Y: Longint;

  end

type Circle =

  object

    Center: Point;

    Radius: Longist;

    procedure Show;

    procedure Hide;

  end;

type Ellipse =

  object (Circle)

    Radius2: Longint;

    Angle: Real;

    procedure Show;

    procedure Rotate(NewAngle: Real);

  end;

Here, the object type Ellipse 'inherits the Center and Radius fields from Circle. It also adds new Radius2 and Angle. Furthermore, it uses the method Hide inherited from Circle; it overrides the method Show and adds a new method, Rotate. The declaration of an object file includes just the headers of the methods. The methods themselves should appear somewhere within the current scope. In this way, method declarations are similar to forwarded routines. When specified, methods names are qualified with object names. For example

procedure Circle.Draw;

begin

  Graph.Circle(X,Y,Radius);

end;

Note that within the method declaration, the fields of the object are visible to the compiler.


Public and Private declarations

Public and private are standard directives in the Object Pascal language. Treat them as if they were reserved words. For readability, it is best to organize an object declaration by visibility, placing all the private members together, followed by all the protected members, and so on. This way each visibility reserved word appears at most once and marks the beginning of a new section of the declaration. So a typical object declaration should look like this:

type

  TObject = object

  private

    { Private declarations }

  public

    { Public declarations }

  end;

The scope of component identifiers declared in private component sections are restricted to the module that contains the object type declaration. Keep in mind that:

•	Inside the module, private component identifiers act like normal public component identifiers.

•	Outside the module, private component identifiers are unknown and inaccessible.

Use the public part to

•	Declare data fields you want methods in objects in other units to access

•	Declare methods you want objects in other units to access

Declarations in the private part are restricted in their access. If you declare fields or methods to be private, they are unknown and inaccessible outside the unit the object is defined in. Use the private part to

•	Declare data fields you want only methods in the current unit to access

•	Declare methods you want only objects defined in the current unit to access


Virtual Methods

Methods can be either static or virtual. Calls to static methods are resolved at compilation. Calls to virtual methods are resolved at run time with delayed or late binding. By default the methods are static; virtual methods contain a special keyword 'virtual' as part of their declaration. Static methods can be overridden without restrictions. However, virtual method override must be done by a method that uses exactly the same syntax, e.g. has the same number and types of the arguments. Objects that contain virtual methods require building a special jump table, called the Virtual Method Table (VMT). The VMT is created during the initialization of the object through a constructor call.


Constructors

Constructors initialize (instantiate) objects by creating and filling their VMT. Any object that uses virtual methods must be first initialized.

type Circle =

  object

    Center: Point;

    Radius: Longint;

    constructor Init(Z:Point; R:Longint);

    procedure   Show; virtual;

    procedure   Hide;

    destructor  Kill;

  end;

var

  C: Circle;

  P: Point;

The following code will instantiate, display, hide, and display the circle C:

P.X:=20;

P.X:=40;

C.Init(P,100);

C.Show;

While Not KeyPressed Do;

C.Hide;

C.Kill;

where:

constructor Circle.Init(Z:Point; R:Longint);

begin

  Center:=P;

  Radius:=R;

end;

Besides initializing the fields of the circle C; C.Init also creates a VMT table. This table is essential for calling a virtual method, such as Show.

Without the C.Init call, the example above will fail (probably cause a run-time exception or halt the system). However, when the example compiled with the range-check {$R+} switch on, TMT Pascal will automatically detect calls from a non-instantiated method and produce a run-time error.

See also:

Destructors

Fail procedure


Fail procedure

Called from within a constructor, Fail causes the constructor to de-allocate a dynamic object it has just allocated.

Declaration:

procedure Fail;

Remarks:

Fail must be called only if one of the constructor's operations fails.


Using New Procedure (OOP)

In most cases, instantiating of an object is combined with allocation of memory for the object:

var C: ^Circle;

begin

  New(C);

  C.Init(P, R);

...

The extended syntax of the New procedure allows one to combine the operation:

var C: ^Circle;

begin

  New(C.Init(P, R));

...

Note that constructors cannot be virtual methods, since virtual methods cannot be called before a constructor initializes the VMT.

See also:

New


Destructors
Desctructors

Destructors are used to clean up after an object is no longer needed. Unlike constructors, destructors can be virtual. Destruction of an object is often combined with deallocation of its memory with the Dispose procedure:

var C: ^Circle;

begin

  New(C);

  C.Init(P,R);

  ...

  C.Kill;

  Dispose(C);

end;

If a constructor fails to perform initialization (often because of its inability to allocate memory for the structures affiliated with the object, it can execute a special system function Fail. Fail signals TMT Pascal to reverse all allocation of the object that might have occurred and return nil as the value of the object's pointer. Fail can be called only within constructors.

See also:

Constructors


Inherited reserved word

Inherited can be used to denote the ancestor of the enclosing method's object type. Inherited can not be used within methods of an object type that has no ancestor.


Self argument

Methods have an additional implicit argument, called Self, which is automatically supplied by the compiler. Self contains the instance of the object for which the method was called. Self, as well, as all of its fields are automatically added to the method's symbol table.


Open Arrays
Opean Arrays

TMT Pascal allows one to use a multidimensional open array as parameter in procedures and functions. The open array parameter has the following format description:

array [dim] of type,

where dim is a positive integer constant, defining the number of dimensions, and type is the type of the array elements. To determine the upper bounds of the array, use the High function. It returns a vector of Longints (array [0..dim-1] of Longint) containing the upper bounds. The lower bounds are always set to 0. The vector of the lower bounds can be obtained with a Low function.

Example:

procedure print_vector (v: array(1) of double);

var i: integer;

begin

  for i := 0 to high(v)[0] do Write(v[i]:10:6, ' ');

  Writeln;

end;

procedure print_matrix(m: array(2) of double);

var i: integer;

begin

  for i := 0 to high (m) [0] do print_vector(m [i]);

  Writeln;

end;

const a: array[1..3, 1..3] of double = ((1,0,2),(2,1,0),(1,2,1));

begin

  print_matrix(a);

end.

You can find an example program for solving a system of linear equations in the EXAMPLES\LIN_EQ directory.


User Defined Operators

TMT Pascal allows redefining of the standard operators on predefined types and overloading of these operators for new types. For this, it uses the construction

overload

The syntax is:

overload op_sign = qualified procedure identifier;

Where the op_sign is one of the standard operator symbols:

+ - / * = <> < > <= >=

and or xor shl shr mod div in not

+:=   -:=   *:=   /:=

When a re-defined operator is used, TMT Pascal uses the last definition that could be applied toward operands of given types. For example, this fragment:

function add_rr (a, b:    Real): Real;

  Result := (a + b) * 2;

function add_ii (a, b: Integer): Integer;

  Result := (a + b) * 2;

overload + = add_rr;

overload + = add_ii;

redefines the "+" operator. Notice that the order of overload's is important. The reverse order

overload + = add_ii;

overload + = add_rr;

will cause add_rr to be used always since integers can always be cast into reals.

In the SOURCES subdirectory you can find the source of the COMP module which realizes the complex numbers and defines the operators on them.

Remarks:

•	The operators +:=, -:=, *:= and /:= have the lowest precedence (lower, than the comparison operators) and are right-associative.

•	The operators "+:=" and "-:=" are predefined for all integer and real types.

•	The operators "*:=" and "/:=" are predefined for all real types, with the obvious meaning.


User Defined Operators

TMT Pascal allows redefining of the standard operators on predefined types and overloading of these operators for new types. For this, it uses the construction

overload

The syntax is:

overload op_sign = qualified procedure identifier;

Where the op_sign is one of the standard operator symbols:

+ - / * = <> < > <= >=

and or xor shl shr mod div in not

+:=   -:=   *:=   /:=

When a re-defined operator is used, TMT Pascal uses the last definition that could be applied toward operands of given types. For example, this fragment:

function add2_rr (a, b:    Real): Real;

  Result := (a + b) * 2;

function add2_ii (a, b: Integer): Integer;

  Result := (a + b) * 2;

overload + = add_rr;

overload + = add_ii;

redefines the "+" operator. Notice that the order of overload's is important. The reverse order

overload + = add_ii;

overload + = add_rr;

will cause add_rr to be used always since integers can always be cast into reals.

In the SOURCES subdirectory you can find the source of the COMP module which realizes the complex numbers and defines the operators on them.

Remarks:

•	The operators +:=, -:=, *:= and /:= have the lowest precedence (lower, than the comparison operators) and are right-associative.

•	The operators "+:=" and "-:=" are predefined for all integer and real types.

•	The operators "*:=" and "/:=" are predefined for all real types, with the obvious meaning.


User Defined Reader Procedure

TMT Pascal compiler allows one to define a reader procedure for ones own types including objects and structures by means of the __reader reserved word. The syntax of the custom reader procedure is the following:

procedure __reader (var f: text; const value: <Custom Type>);

begin

  ...

end;

The __reader example below showed the use of a DateTime structure defined in the DOS unit. This code reads a date using the Read procedure:

{$ifdef __GUI__}

uses DOS, WinCRT;

{$else}

uses DOS;

{$endif}

procedure __reader (var f: text; const value: DateTime);

begin

  Read(f, value.Month, value.Day, value.Year);

end;

var

  date: DateTime;

begin

  Read(date);

end.

See also

__writer


User Defined Writer Procedure

TMT Pascal compiler allows one to define a writer procedure for ones own types including objects and structures by means of the __writer reserved word. The syntax of the custom writer procedure is the following:

procedure __writer (var f: text; const value: <Custom Type>; w: Integer);

begin

  ...

end;

The __writer example below showed the use of a DateTime structure defined in the DOS unit. A date is an ideal candidate for a Pascal structure in which the data members (month, day, and year) are hidden from view. An output file is the logical destination for displaying such a structure. This code displays a date using the Write procedure:

{$ifdef __GUI__}

uses DOS, WinCRT;

{$else}

uses DOS;

{$endif}

procedure GetCurrentDate(var date: DateTime);

var

  Year, Month, Day, DayOfWeek: Word;

begin

  GetDate(Year, Month, Day, DayOfWeek);

  date.Year := Year;

  date.Month := Month;

  date.Day := Day;

end;

procedure __writer (var f: text; const value: DateTime; w: Integer);

begin

  Write(f, value.Month, '/', value.Day, '/', value.Year);

end;

var

  date: DateTime;

begin

  GetCurrentDate(date);

  Writeln(date);

end.

When you run this program, it prints the current date.

See also

__reader


Built-in Assembler

TMT Pascal allows to mix assembly language code with Pascal using two distinct methods:

•	Using External assembly files, compiled with a suitable 32-bit assembler. These can be linked in with the {$L} Pascal directive.

•	Using the built-in assembly code which can be placed inside Pascal source files.

This chapter describes the built-in assembler (BASM).

Since the program created by the TMT Pascal is executed in the flat model, the far call and jump commands as well as the @Code and @Data symbols are not implemented.

Asm Statement

Assembler Procedure

Code Procedure

Command Syntax

Labels

Prefixes

Opcodes

Registers

Opcode Mnemonics

Operand Expressions

Operands

Operators

Operator Precedence

Differences between 16- and 32-bit code


Asm Statement

The built-in assembler is invoked with the asm statement. The syntax of the

asm statement is

asm

  [AssemblerStatement(s)]

end;

The asm statement may appear anywhere where a Pascal statement allowed.

asm

  MOV  Al, Value

  MOV  DX, ThePort

  OUT  DX, AL

end;


Assembler Procedure

The built-in assembler can also be used to write entire procedures in assembler language. Such procedures should have the Assembler keyword appended after a procedure header.

function MultBy9(X: Longint): Longint;

Assembler;

  asm

    MOV  EAX,[X]

    LEA  EAX,[EAX*8+EAX]

end;

The function above used i80386 index scaling feature to implement very fast multiplication by 9.

The Assembler procedures differ from the standard Pascal procedures in the following ways:

No Return variable

There is no return variable. You must return the function results in an appropriate register. More precisely,

•	Ordinal values are returned in AL (8-bit values), AX (16-bit values), or EAX (32-bit values).

•	Real values are returned in DX:BX:AX.

•	Floating point (8087) values are returned in ST(0).

•	Pointers are returned in EAX.

•	Strings are returned in a temporary location pointed by the @Result symbol.

Structured variables

Structured arguments (i.e. strings, objects, records) are not copied into the local variables. They should be treated as Var parameters.

Stack Frame

Assembler procedures have no stack frames if they have no arguments and no

local symbols. Generally, the stack frame supplied by the built-in assembler is

PUSH   EBP         // Appears if locals + params >0

MOV    EBP,ESP     // Appears if locals + params >0

SUB    ESP, locals // Appears if locals + params >0

...

LEAVE              // Appears if locals + params >0

RETN   params      // Always appears

Here Locals is the total size of local parameters, Params is the total size of procedure parameters.

Register Preservations

Assembler code should preserve the following registers: DS, CS, SS, ES, EBP, and ESP. All other registers can be destroyed. Notice the inclusion of the ES register. TMT Pascal always assumes that ES is equal to DS.

Furthermore, you should not change segment, page, and interrupt tables, as well as the control, debug and test registers, unless you are thoroughly familiar with 386 protected mode architecture. The privileged instructions like LGDT and LIDT are supported by built-in assembler. However, avoid using them unless you know exactly what you are doing.


Code Procedure

Besides the assembler-routine you can use the code-routine. It has the following differences: the compiler doesn't emit the frame command on enter and return from the routine (including the ret command), and the local parameters are based on ESP on the moment of entry.

Example:

function hi (n: word); code;

  asm

    mov al, byte ptr [n+1]

    ret

end;


Command Syntax

The general syntax of an assembler statement is

 [label:]

 [prefixes]

 [[opcode [operand1 [,operand2 [,operand3]]]]

Here:

label: is an optional label definition;

prefixes are instruction prefixes;

opcode is a instruction mnemonic or directive;

operand is an operand expression.


Assembler Labels

The built-in assembler allows two types of labels:

•	Global labels are declared inside a Pascal program within label declarations. Global labels are identical to Pascal labels.

•	Local labels are not declared. They must start with the @ symbol and contain letters, digits, or underscore characters. Local labels are visible only within the current asm statement.

Labels can be used with any assembler statements. More than one label can be used, if needed. Labels are always optional.


Assembler Prefixes

Prefixes are modifiers for the following instruction. TMT Pascal allows the following prefix mnemonics:

* SEGCS           Override the operand's segment with CS:

* SEGDS           Override the operand's segment with DS:

* SEGES           Override the operand's segment with ES:

* SEGFS           Override the operand's segment with FS:

* SEGGS           Override the operand's segment with GS:

* SEGSS           Override the operand's segment with SS:

* LOCK            Lock the bus

* REP             Repeat the instruction

* REPE  and REPZ  Repeat while equal

* REPNE and REPNZ Repeat while not equal


Assembler Opcodes

The opcodes are either instruction mnemonics or assembly directives. The list of supported instruction opcodes is given below. The only assembly directives that are allowed in TMT Pascal are DB, DW, and DD.

Example

asm

  DB  'a','b','c'

  DB  'This code was copyrighted by GnueWare'

  DW  1,2,4,8,16,$20,40h

  DD  Offset HeapLo

end;

The DB, DW, and DD directive allow variable number of arguments, separated by commas. The other commonly used assembly directives can be emulated with Pascal statements. For instance, the EQU directive is emulated with const, while STRUCT's can be defined with the type record declaration.


Assembler Registers

The following registers can appear in built-in assembler:

 8-bit:      AL BL CL DL AH BH CH DH

 16-bit:     AX BX CX DX SI DI BP SP

 32-bit:     EAX EBX ECX EDX ESI EDI EBP ESP

 Segment:    CS DS ES SS FS GS

 8087:       ST

 Control:    CRn

 Debug:      DRn

 Test:       TRn

The segment register can be used for segment overrides. 32-bit registers can be used for indexation following the standard 80386 conventions. 16-bit registers should never be used for addressing, unless your entire program does not exceed 64K. Even then, addressing with 16-bit registers is inefficient. Generally, an address is formed as

Base + Index * Scale + Displacement

where Base is any of the 32-bit registers, Index is any 32-bit register but not ESP, and Scale should be 1,2,4, or 8. Finally, the Displacement is a 32-bit integer quantity.

Here are some valid and invalid indexing modes:

  [EAX+EBX]; ok

  [EAX+EAX]; ok, EAX is both base and index.

      [ESP]; ok, ESP is index, no base.

    [EDX*2]; ok, use this to index a global array of words.

[EAX*4+EBP]; ok, use this to index a local array of longints.

       [SI]; ok, but is likely to lead to hard-to-find bugs.

   [ESI+BX]; illegal, mix of 16- and 32- bit registers.

     [SI*4]; illegal, 16-bit registers cannot be scaled.

    [ESP*4]; illegal, ESP cannot be an index.

Please consult Intel™ 80386/80486 Programmer’s reference for more details.


Assembler Opcode Mnemonics

This section lists valid opcode mnemonics. Please consult an 80386 reference book for additional details. The list uses the following abbreviations:

* acc   - accumulator register (AL, AX, EAX)

* brm   - byte register or memory operand

* cdt   - control, debug or test register

* imm   - byte

* label - offset in code

* mem   - memory operand

* none  - no operands

* reg   - register

* rm    - register or memory operand

* seg   - segment register

* st    - coprocessor top of stack register

* st(i) - coprocessor register

 Opcode:     Possible arguments

    AAA:      none

    AAD:      none

    AAM:      none

    AAS:      none

    ADC:      rm,reg | reg,rm | rm,imm

    ADD:      rm,reg | reg,rm | rm,imm

    AND:      rm,reg | reg,rm | rm,imm

   ARPL:      rm,reg

  BOUND:      reg,mem

    BSF:      reg,rm

    BSR:      reg,rm

    BTC:      rm,reg | rm,imm

    BTR:      rm,reg | rm,imm

    BTS:      rm,reg |rm,imm

    BT:       rm,reg | rm,imm

   CALL:      label | rm

    CBW:      none

    CDQ:      none

    CLC:      none

    CLD:      none

    CLI:      none

   CLTS:      none

    CMC:      none

    CMP:      rm,reg | reg,rm | rm,imm

  CMPSB:      none

  CMPSD:      none

  CMPSW:      none

  CPUID:      none

    CWD:      none

   CWDE:      none

    DAA:      none

    DAS:      none

    DEC:      rm

    DIV:      rm

  ENTER:      imm,imm

  F2XM1:      none

   FABS:      none

   FADD:      none | st,st(i) | st(i),st | mem

  FADDP:      st(i),st

   FBLD:      mem

  FBSTP:      mem

   FCHS:      none

  FCLEX:      none

   FCOM:      none | st(i) | mem

  FCOMP:      none | st(i) | mem

 FCOMPP:      none

FDECSTP:      none

  FDISI:      none

   FDIV:      none | st,st(i) | st(i),st | mem

  FDIVP:      st(i),st

  FDIVR:      st(i),st

 FDIVRP:      st(i),st

   FENI:      none

  FFREE:      st(i)

  FIADD:      mem

 FICOMP:      mem

  FICOM:      mem

 FIDIVR:      mem

  FIDIV:      mem

   FILD:      mem

  FIMUL:      mem

  FIMUL:      mem

FINCSTP:      mem

  FINIT:      none

   FIST:      mem

  FISTP:      mem

  FISUB:      mem

 FISUBR:      mem

    FLD:      st(i) | mem

   FLD1:      none

  FLDCW:      mem

 FLDENV:      none

 FLDL2E:      none

 FLDL2T:      none

 FLDLG2:      none

 FLDLN2:      none

  FLDPI:      none

   FLDZ:      none

   FMUL:      none | st,st(i) | st(i),st | mem

  FMULP:      none | st(i),st

 FNCLEX:      none

 FNDISI:      none

  FNENI:      none

 FNINIT:      none

   FNOP:      none

 FNSAVE:      none

 FNSTCW:      none

FNSTENV:      none

 FNSTSW:      none

 FPATAN:      none

  FPREM:      none

 FPREM1:      none

  FPTAN:      none

FRNDINT:      none

 FRSTOR:      mem

  FSAVE:      mem

 FSCALE:      none

 FSETPM:      none

  FSQRT:      none

    FST:      st(i) | mem

   FSTP:      st(i) | mem

  FSTCW:      mem

 FSTENV:      mem

  FSTSW:      mem | AX

   FSUB:      none | st,st(i) | st(i),st | mem

  FSUBP:      none | st(i)st

  FSUBR:      none | st,st(i) | st(i),st | mem

 FSUBRP:      none | st(i),st

   FTST:      none

  FWAIT:      none

   FXAM:      none

   FXCH:      none

FXTRACT:      none

FYL2XP1:      none

  FYL2X:      none

    HLT:      none

   IDIV:      rm

   IMUL:      rm | reg,imm | reg,rm,imm

     IN:      acc,imm | acc,DX

    INC:      rm

   INSB:      none

   INSD:      none

   INSW:      none

    INT:      imm

   INTO:      none

  IRETD:      none

   IRET:      none

     JA:      label

    JAE:      label

     JB:      label

    JBE:      label

     JC:      label

   JCXZ:      label

     JE:      label

  JECXZ:      label

     JG:      label

    JGE:      label

     JL:      label

    JLE:      label

    JMP:      label | rm

    JNA:      label

   JNAE:      label

    JNB:      label

   JNBE:      label

    JNC:      label

    JNE:      label

    JNG:      label

   JNGE:      label

    JNL:      label

   JNLE:      label

    JNO:      label

    JNP:      label

    JNS:      label

    JNZ:      label

     JO:      label

     JP:      label

    JPE:      label

    JPO:      label

     JS:      label

     JZ:      label

   LAHF:      none

    LAR:      reg,rm

    LDS:      reg,mem

  LEAVE:      none

    LEA:      reg,mem

    LES:      reg,mem

    LFS:      reg,mem

   LGDT:      mem

    LGS:      reg,mem

   LIDT:      mem

   LLDT:      rm

   LMSW:      rm

  LODSB:      none

  LODSD:      none

  LODSW:      rm

   LOOP:      label

 LOOP16:      label

 LOOP32:      label

  LOOPE:      label

 LOOPNE:      label

 LOOPNZ:      label

  LOOPZ:      label

    LSL:      reg,rm

    LSS:      reg,mem

    LTR:      reg,mem

    MOV:      reg,rm|rm,reg|rm,imm|rm,seg|seg,rm|reg,cdt|cdt,reg

  MOVSB:      none

 MOVSD:      none

  MOVSW:      none

  MOVSX:      reg,rm

  MOVZX:      reg,rm

    MUL:      rm

    NEG:      rm

    NOP:      none

    NOT:      rm

     OR:      none

    OUT:      imm,acc | DX,acc

  OUTSB:      none

  OUTSD:      none

  OUTSW:      none

    POP:      rm

   POPA:      none

  POPAD:      none

   POPF:      none

  POPFD:      none

   PUSH:      rm

  PUSHA:      none

 PUSHAD:      none

 PUSHF:      none

 PUSHFD:      none

    RCL:      rm,1 | rm,CL | rm,imm

    RCR:      rm,1 | rm,CL | rm,imm

    RET:      none,imm

   RETF:      none,imm

   RETN:      none,imm

    ROL:      rm,1 | rm,CL | rm,imm

    ROR:      rm,1 | rm,CL | rm,imm

   SAHF:      none

    SAL:      rm,1 | rm,CL | rm,imm

    SAR:      rm,1 | rm,CL | rm,imm

    SBB:      rm,reg | reg,rm | rm,imm

  SCASB:      none

  SCASD:      none

  SCASW:      none

  SEGCS:      none

  SEGDS:      none

  SEGES:      none

  SEGSS:      none

  SEGFS:      none

  SEGGS:      none

   SETA:      brm

  SETAE:      brm

   SETB:      brm

  SETBE:      brm

   SETC:      brm

   SETE:      brm

  SETGE:      brm

   SETG:      brm

   SETL:      brm

  SETLE:      brm

  SETNA:      brm

 SETNAE:      brm

 SETNBE:      brm

  SETNB:      brm

  SETNC:      brm

  SETNE:      brm

 SETNGE:      brm

  SETNG:      brm

 SETNLE:      brm

  SETNL:      brm

  SETNO:      brm

  SETNP:      brm

  SETNS:      brm

  SETNZ:      brm

   SETO:      brm

  SETPE:      brm

  SETPO:      brm

   SETP:      brm

   SETS:      brm

   SETZ:      brm

   SGDT:      mem

   SHLD:      rm,reg,imm

    SHL:      rm,1 | rm,CL | rm,imm

   SHRD:      rm,reg,imm

    SHR:      rm,1 | rm,CL | rm,imm

   SIDT:      mem

   SLDT:      rm

   SMSW:      rm

    STC:      none

    STD:      none

    STI:      none

  STOSB:      none

  STOSD:      none

  STOSW:      none

    STR:      rm

    SUB:      rm,reg | reg,rm | rm,imm

   TEST:      rm,reg | reg,rm | rm,imm

   VERR:      rm

   VERW:      rm

   WAIT:      none

   XCHG:      reg,rm | rm,reg

   XLAT:      none

    XOR:      rm,reg | reg,rm | rm,imm


Assembler Operand Expressions

Operand expressions are built from operands and operators. Operands are constants, registers, labels, and memory locations. Operators combine operands and alter their attributes. Each instruction allows only certain combinations of operands.

Operand expressions can be classified into three classes:

•	Immediate operands or constants.

•	Registers.

•	Memory and label operands.

Immediate operands

 PUSH  10

 MOV   AX, 10

 MOV   AX, offset Start

Here 10, and Star' are immediate operands. The values of A and 10 can be determined immediately; the value of offset Start is determined during linking.

Registers

TMT Pascal built-in assembler allows use of any 8, 16, or 32-bit 80386 registers.

 XOR  AH, AL

 LSL  EAX,EAX

 MOV  AX, FX

Memory and label operands

Memory operands refer to the data stored in memory locations. Usually, one uses the square brackets [..] or the type ptr operator to ensure that the argument is treated as a memory location. Label operands refer to locations in code.

 MOV      EBX,[0]

 POP      Word Ptr [88]

 POP      Word Ptr 88  // same as above

 JMP      @exit

 LOOP16   @loop

Memory and immediate operands can be either absolute or relocatable. An operand is absolute if its value or offset is entirely known during compilation. An operand is relocatable if its offset will become known only during linking.


Assembler Operands

TMT Pascal allows the following operands: Numeric Constants, Strings, Registers, Pascal Symbols and Special Assembler Symbols.

Numeric Constants

Numeric constants are 32-bit integers, e.g. integers in the range -2147483648..4294967295. Numeric constants can be entered as decimal numbers binary numbers (using the 'B' suffix), octal numbers (using the 'O' or 'Q' suffix), hexadecimal numbers (using the 'H' suffix or '$' prefix). Note that the hexadecimal numbers must start with a digit.

Strings

Strings are enclosed in either single or double quotes. A repeated quote of the same type as the surrounding quotes is treated as one character. String constants of arbitrary length may occur only in the 'DB' directive. In all other cases, the string must not exceed four characters and its value is converted into an integer number.

Registers

The use of registers was described above.

Pascal Symbols

With built-in assembler you can access the majority of Pascal symbols. These include labels, constants, variables, types, and procedures. The values, classes and types of Pascal symbols are summarized in the table below:

Symbol     Value        Class      Type

label      its address  Memory     NEAR

constant   its value    Immediate  0

type       0            Memory     sizeof(type)

field      its offset   Memory     sizeof(type)

variable   its address  Memory     sizeof(type)

procedure  its address  Memory     NEAR

function   its address  Memory     NEAR

unit       its address  Immediate  0

Special Assembler Symbols

Built-in assembler supports five special symbols: @CODE, @DATA, @RESULT, @PARAMS and @LOCALS. The @CODE and @DATA are not really useful in a flat model. They always return 0Ch and 14h, which are the standard segment selectors for the code and data segments. The @RESULT symbol points to the pseudo-variable that contains the function return, @PARAMS and @LOCALS return the size of the parameter and local areas on stack.


Assembler Operators

TMT Pascal built-in assembler syntax allows the a number of operators, listed below:

&	Identifier override operator. The following identifier is considered to be a user defined symbol, even if its spelling is identical to an assembler reserved word.
()	Parenthesis. Expressions within parenthesis are evaluated first.
[]	Memory reference. The expression within brackets is evaluated first. This expression should be a valid 386 address. The resulting expression is always treated as a memory reference.
HIGH, LOW	High and Low byte selection. These operators return the high and low 8 bits of the word-size expression that follows.
+, -	Unary plus and minus operators. The expression should be an absolute immediate.
SMALL, LARGE	Forces the built-in assembler to treat the following operands as a 16- or 32- bit quantity.
OFFSET	Returns the 32-bit offset of the expression that follows.
SEG	Returns the segment part of the operand.
TYPE	Returns the type of the operand. The type of a NEAR symbol is -1, of a FAR symbol is -2. The type of a memory operand is its size. The type of an immediate symbol is 0.
PTR	Typecasts the following expression into the type symbol that precedes the PRT operator. Valid typecasts are BYTE PRT, WORD PRT, DWORD PRT, FWORD PRT, TBYTE PRT, QWORD PRT, NEAR PRT, and FAR PRT.
*	Multiplication. Both arguments must be absolute immediate quantities, or one of the arguments should be an index register and the other a scale factor (1,2,4, or 8).
/	Division. Both arguments must be absolute immediate quantities.
MOD	Integer remainder after division. Both arguments must be absolute immediate quantities.
SHL, SHR	Left and right shifts. Both arguments must be absolute immediate quantities.
+, -	Addition and Subtraction. At most one arguments can be a relocatable value and it cannot be the argument that is being subtracted. The other argument must be an absolute immediate quantity.
NOT	Binary complement. The argument must be an absolute immediate quantity.
AND	Bitwise AND. The arguments must be absolute immediate quantities.
OR	Bitwise OR. The arguments must be absolute immediate quantities.
XOR	Bitwise exclusive OR. The arguments must be absolute immediate quantities.


Assembler Operator Precedence

The precedence of these operators is shown in the following table (from the highest precedence to the lowest):

 Operator              Comments

 &                     Identifier override

 () []                 Sub-expressions, memory reference,

                       structure member

 HIGH LOW              High and low bytes selectors

 LARGE SMALL           32- and 16- bit operation overrides

 + -                   Unary operators

 :                     Segment override

 OFFSET SEG TYPE

 PTR */MOD SHL SHR

 + -                   Binary operators

 NOT AND OR XOR        Bitwise operators


Differences between 16- and 32-bit code

While this manual does not really teach 32-bit assembly programming, we will list here several considerations important in 32-bit assembler programming. These considerations may be helpful to a 16-bit programmer entering the 32-bit arena.

Avoid using 16-bit registers for indexation

The built-in assembler will correctly assemble instructions like

 MOV       BX,offset table

 MOV       AX,table[BX]

 JMP       table[BX]

However, these instructions will not work correctly if the size of your program exceeds 64K and the 'table' variable is placed after the 64K limit. This is because 16-bit addresses span only the 64K of the segment. The last example above is the most dangerous; it is likely to crash the system.

Jump tables

Jump tables should be build as tables of 32-bit addresses, not 16-bit addresses.

Longint (32-bit) Arithmetic

Try to use the longint arithmetic as much as possible. 16-bit instructions often take more space than corresponding 32-bit instructions. In

 XOR     AX,    AX

 MOV     data1, AX

 MOV     data2, AX

it would be better to replace the first instruction with

 XOR     EAX, EAX

which is one byte shorter. Furthermore, if data1 and data2 can be changed into longints, you may save a lot more space (and time) both in the assembler and the Pascal sections of the program.

ECX vs CX

Loop and repeat instructions in 32-bit mode use the ECX register rather than CX. The following program segment is likely to cause problems:

 MOV    CX,  size

 MOV    ESI, source

 MOV    EDI, dest

 REP    MOVSB

Also notice that the source and destination registers are ESI and EDI, rather than SI and DI.

POPAD/PUSHAD

Use POPAD and PUSHAD instead of POPA and PUSHA. The latter instructions generate only 16-bit pushes.

POPFD/PUSHFD

Use POPFD and PUSHFD instead of POPF and PUSHF. The latter instructions generate only 16-bit pushes.

IRETD

Use 'IRETD' instead of 'IRET'. The latter instruction pops 16-bit registers.

String instructions

When doing string operations, it is later to use double word instructions instead of byte or word. Use MOVSD instead of MOVSW or MOVSB.

JECXZ vs JCXZ

Distinguish between the JCXZ and JECXZ instructions. The former tests the CX register, while the latter tests ECX. Use of JCXZ instead of JECXZ may lead to hard-to-find bugs. Similarly, LOOP tests ECX, while LOOP16 tests CX.

Function results

Remember to return 32-bit results in EAX, not DX:AX.

ES: preservations

Do not change the ES register. TMT Pascal depends on ES = DS.

Immediate PUSH

TMT Pascal assumes that an immediate push instruction like

  PUSH    Small 0

  PUSH    Small offset data

Furthermore notice that like TASM and unlike the PharLap assembler, TMT Pascal will treat

  PUSH    Word Ptr 0

as if it were

  PUSH    Word Ptr [0]

Var Parameters

Similar to 16-bit mode, var parameters are 32-bit pointers. However, in TMT Pascal, pointers are just 32-bit offsets within the data segment. Therefore, var parameters are retrieved with a 'MOV' instruction, not with an LES or an LDS.

Local Symbols

Local Symbols and Parameters are addressed via the EBP register. For example, in

var

  local: Longint;

asm

  MOV   EAX, local

end;

the last line assembles into

  MOV   EAX, [EBP-4]


Run-time Error Codes

The following error codes are predefined:

Code                            Meaning

1	Invalid function number

2	File not found

3	Path not found

4	Too many open files

5	File access denied

6	Invalid file handle

12	Invalid file access code

15	Invalid drive number

16	Cannot remove current directory

17	Cannot rename across drives

18	No more files

100	Disk read error

101	Disk write error

102	File not assigned

103	File not open

104	File not open for input

105	File not open for output

106	Invalid numeric format

150	Disk is write protected

151	Bad drive request structure length

152	Drive not ready

154	CRC error in data

156	Disk seek error

157	Unknown media type

158	Sector not found

159	Printer out of paper

160	Device write fault

161	Device read fault

162	Hardware failure

200	Division by zero

201	Range check error

202	Stack overflow error

203	Heap overflow error

204	Invalid pointer operation

205	Floating point overflow

206	Floating point underflow

207	Invalid floating point operation

208	Overlay manager not installed

209	Overlay file read error

210	Object not initialized

211	Call to abstract method

212	Stream registration error

213	Collection index out of range

214	Collection overflow error

215	Arithmetic overflow error

216	General protection fault

217	Invalid operation code

300	File IO error

301	Non matched array bounds

302	Non local procedure pointer

303	Procedure pointer out of scope

304	Function not implemented

305	Breakpoint error

306	Break by Ctrl/C

307	Break by Ctrl/Break

308	Break by other process

309	No floating point coprocessor


Standard Units

TMT Pascal comes with 16 standard units. It is also possible to create your own units. For example, in writing a large program it might become desirable to group display routines or user input routines. This allows for greater organization while programming. For more information on creating your own units see the Programs and Units chapter.

The following is a list of the standard units that are supplied with TMT Pascal.

CompMath

CRT

Debug

Dos

DPMI

ErrCodes

FDebug

Graph

Keyboard

Math

Mouse

Printer

Strings

System

Use16

Use32

WinDos

ZenTimer


TMT Pascal Developer’s Help System revision 2.50.

Copyright © 1995-2002 by TMT Development Corporation. All rights reserved.


Compiler Directives

Compiler directives, are comments started with $ symbol. Compiler directives can be used wherever comments are allowed.

Compiler directives

−	begin with {$, /*$ or (*$

−	are followed by the name of the directive

−	end with }, */ or *)

Note that // and –- comments can not be used to specify compiler directive

Compiler directives come in three varieties:

•	Switch directives turn compiler features on or switches off when + or - are specified after the directive name.

•	Parameter directives specify parameters that affect the compilation.

•	Conditional directives control conditional compilation of parts of the source text.

Conditional Directives

Switch and Parameter Directives

Predefined Symbols


Switch and Parameter Directives

$A: Data Align Switch

$AC: Ada-Style Comments Switch

$AMD: AMD 3DNow! Assembler Instructions Switch

$B: Boolean Evaluation Switch

$CC: C/C++ Style Comments Switch

$D: Debug Information Switch

$I: I/O-Checking Switch

$I: Include File Directive

$L: Link Object File Directive

$L: Local Symbol Information Switch

$MAP: Map File Generation Switch

$MMX: Intel MMX Assembler Instructions Switch

$OA: Objects and Structures Align Switch

$OPT: Full Optimization Switch

$OPTFRM: Stack Frame Optimization Switch

$OPTREG: Register Optimization Switch

$P: Open String Parameters Switch

$Q: Overflow Checking Switch

$R: Range-Checking Switch

$S: Stack-Overflow Checking Switch

$T: Type-Checked Pointers Switch

$TPO: Typed Inc/Dec Operations Switch

$V: Var-String Checking Switch

$W: Warnings Generation Switch

$X: Extended Syntax Switch

$XW: Extended Warnings


Conditional directives

Compiler directives

Conditional compilation is based on the evaluation of conditional symbols.

$DEFINE	Defines a conditional symbol

$ELSE	Compiles or ignores a portion of source text

$ENDIF	Ends the conditional compilation

$IFDEF	Compiles source text if Name is defined

$IFNDEF	Compiles source text if Name is NOT defined

$IFOPT	Compiles source text if a compiler switch is in a specifies state (+ or -)

$UNDEF	Undefines a previously defined conditional symbol


$A: Data Align Switch

Compiler directives

Switches on/off word-alignment of variables and typed constants

Syntax:

  {$A+} or {$A-}

Default:

  {A+}

Remarks:

The data align switch has no affect on structures and objects alignment. Use $OA compiler directive to switch on/off structures and objects alignment.


$AC: Ada-Style Comments Switch

Compiler directives

Switches on/off Ada-style comments recognition.

Syntax:

  {$AC+} or {$AC-}

Default:

  {AC-}

Remarks:

Keep in mind that Ada-style comments are not longer supported by default.


$AMD: AMD 3DNow! Assembler Instructions Switch

Compiler directives

Enables/disables AMD 3DNow! instructions support in built-in assembler.

Syntax:

  {$AMD+} or {$AMD-}

Default:

  {AMD+}


$B: Boolean Evaluation Switch

Compiler directives

Switches on/off the two different models of code generation for the AND and OR Boolean operators.

Syntax:

  {$B+} or {$B-}

Default:

  {$B-}

Remarks:

If {$B+} defined, the compiler generates code for complete boolean expression evaluation. I.e. every operand of a boolean expression built from the AND and OR operators is guaranteed to be evaluated, even when the result of the entire expression is already known.

If {$B-} defined, the compiler generates code for short-circuit boolean-expression evaluation. I.e. evaluation stops as soon as the result of the entire expression becomes evident.


$CC: C/C++ Style Comments Switch

Compiler directives

Switches on/off C/C++ style comments recognition.

Syntax:

  {$CC+} or {$CC-}

Default:

  {CC+}


$D: Debug Information Switch

Compiler directives

Switches on/off  the generation of debug information.

Syntax:

  {$D+} or {$D-}

Default:

  {$D+}

Remarks:

Debug information consists of a line-number table for each procedure. The table maps object-code addresses into source-text line numbers.

If {$D+} defined, you can use built-in Debugger to single-step, step over and set breakpoints in that module.

Debug information increases the size of unit files and increases memory usage when you compile programs that use the unit.

The Debug Information switch is usually used with the Local Symbols switch.

See also:

$L: Local Symbol Information Switch.


$I: I/O-Checking Switch

Compiler directives

Enables or disables the automatic code generation that checks the result of a call to an I/O procedure.

Syntax:

  {$I+} or {$I-}

Default:

  {$I+}

Remarks:

If an I/O procedure returns a non-zero I/O result when the $I switch is on, the program terminates, displaying a run-time error message.

When the $I switch is off, you should use the IOResult function to check for I/O errors.


$I: Include File Directive
$Include File Directive

Compiler directives

Instructs the compiler to include the named file in the compilation.

Syntax:

  {$I FileName}

Remarks:

The included file is inserted in the compiled text right after the {$I FileName} directive.


$L: Link Object File Directive

Compiler directives

Instructs the compiler to link the named file with the program or unit being compiled.

Syntax:

  {$L FileName}

Remarks:

The {$L FileName} directive is used to link with code written in assembly language for subprograms declared to be external.

The named file must be an Intel relocatable object file (.OBJ file).

See also:

External Declaration


$L: Local Symbol Information Switch

Compiler directives

Enables or disables the generation of local symbol information.

Syntax:

  {$L+} or {$L-}

Default:

  {$L+}

Remarks:

Local symbol information consists of the symbols in the module's implementation part (names and types of all local variables and constants in a module), and the symbols within the module's procedures and functions


$MAP: Map File Generation Switch

Compiler directives

Switches on/off warnings generation.

Syntax:

  {$MAP+} or {$MAP-}

Default:

  {MAP-}

Remarks:

If {$MAP+} defined, TMT Pascal will generate a map file.


$MMX: Intel MMX Assembler Instructions Switch

Compiler directives

Enables/disables Intel MMX instructions support in built-in assembler.

Syntax:

  {$MMX+} or {$MMX-}

Default:

  {MMX+}


$OA: Objects and Structures Align Switch

Compiler directives

Switches on/off word-alignment of objects and structures.

Syntax:

  {$OA+} or {$OA-}

Default:

  {OA-}

Remarks:

The data align switch has no affect on variables and typed constants alignment. Use $A compiler directive to switch on/off variables and typed constants alignment.


$OPT: Full Optimization Switch

Compiler directives

Switches on/off full optimization ({OPTREG+} & {OPTFRM+}).

Syntax:

  {$OPT+} or {$OPT-}

Default:

  {OPT+}


$OPTFRM: Stack Frame Optimization Switch

Compiler directives

Switches on/off stack frame optimization.

Syntax:

  {$OPTFRM+} or {$OPTFRM-}

Default:

  {OPTFRM+}


$OPTREG: Register Optimization Switch

Compiler directives

Switches on/off register optimization.

Syntax:

  {$OPTREG+} or {$OPTREG-}

Default:

  {OPTREG+}


$P: Open String Parameters Switch

Compiler directives

Controls the meaning of variable parameters declared using the string keyword.

Syntax:

  {$P+} or {$P-}

Default:

  {$P+}

Remarks:

If {$P-} defined, variable parameters declared using the string keyword are normal variable parameters

If {$P+} defined, variable parameters declared using the string keyword are open string parameters.


$Q: Overflow Checking Switch

Compiler directives

Controls the generation of overflow checking code.

Syntax:

  {$Q+} or {$Q-}

Default:

  {$Q-}

Remarks:

The $Q switch is usually used in conjunction with the $R switch.

Enabling overflow checking slows down your program and makes it larger. We recommend to use {$Q+} only for debugging purposes.


$R: Range-Checking Switch

Compiler directives

Enables and disables the generation of range-checking code

Syntax:

  {$R+} or {$R-}

Default:

  {$R-}

Remarks:

The $R switch is usually used in conjunction with the $Q switch.

If {$R+} defined, all array and string-indexing expressions are verified as being within the defined bounds all assignments to scalar and subrange variables are checked to be within range.

If a range-check fails, the program terminates and displays a run-time error message.

Enabling range-checking slows down your program and makes it larger. We recommend to use {$R+} only for debugging purposes.

Keep in mind that range-checking mode affects even on “+“, “*“ and Shl operators.


$S: Stack-Overflow Checking Switch

Compiler directives

Enables and disables the generation of stack-overflow checking code.

Syntax:

  {$S+} or {$S-}

Default:

  {$S-}

Remarks:

If {$S+} defined, the compiler generates code at the beginning of each procedure or function to check whether there is sufficient stack space for the local variables and other temporary storage.

Important! This option is not supported by current version of compiler and will be ignored.


$T: Type-Checked Pointers Switch

Compiler directives

Controls the types of pointer values generated by the @ operator.

Syntax:

  {$T+} or {$T-}

Default:

  {$T-}

Remarks:

If {$T-} defined, the result type of the @ operator is always an untyped pointer. Otherwise the type of the result is ^T, where T is compatible only with other pointers to the type of the variable.


$TPO: Typed Inc/Dec Operations Switch

Compiler directives

Enables/disables typed Inc/Dec operations on pointers.

Syntax:

  {$TPO+} or {$TPO-}

Default:

  {$T+}

Example:

var

  a: ^DWORD;

begin

  a := Pointer(0);

  inc(a);

  Writeln(Longint(a));

end.

The sample above prints 1 if typed operations are disabled ($TPO-}. If typed operations are enabled ($TPO+}, the application prints 4.


$V: Var-String Checking Switch

Compiler directives

Controls type-checking on strings passed as variable parameters.

Syntax:

  {$V+} or {$V-}

Default:

  {$V+}

Remarks:

If {$V+} defined, strict type-checking is performed, requiring the formal and actual parameters to be of identical string types. Otherwise any string-type variable is allowed as an actual parameter, even if the declared maximum length is not the same as that of the formal parameter.


$W: Warnings Generation Switch

Compiler directives

Switches on/off warnings generation.

Syntax:

  {$W+} or {$W-}

Default:

  {W+}

Remarks:

If {$W+} defined, TMT Pascal will show compilation warnings.


$X: Extended Syntax Switch

Compiler directives

Enables or disables Turbo Pascal's extended syntax.

Syntax:

  {$X+} or {$X-}

Default:

  {$X+}

Remarks:

If {$X+} defined, function calls can be used as statements; the result of a function call can be discarded.


$XW: Extended Warnings Generation Switch
$XW: Extended Warnings Switch

Compiler directives

Switches on/off extended warnings generation.

Syntax:

  {$XW+} or {$XW-}

Default:

  {$XW-}

Remarks:

If {$XW+} defined, TMT Pascal will show compilation warnings.


Predefined Symbols

Compiler directives

The following symbols are predefined:

MSDOS	- for DOS target

__TMT__	- always

__VER3__	- always for version 3.xx

__MULTITARGET__	- always for TMT Pascal multi-target

__DOS__	- for DOS target

__OS2__	- for all OS/2 targets

__DLL__	- for OS/2 and Win32 DLL targets

__PM__	- for OS/2 Presentation manager targets

__FS__	- for OS/2 Full Screen targets

__WIN32__	- for all Win32 targets

__CON__	- for OS/2, Win32 and MS-DOS console targets

__GUI__	- for Win32 GUI targets


The CompMath Unit

Targets: MS-DOS, OS/2, Win32

The CompMath unit provides procedures and functions to manipulate complex numbers, including standard arithmetic operations, relational operators and extended trigonometrically functions. Is also overloads the standard arithmetic and rationaloperators, and defines the system __reader and __writer functions for a Complex type.

CompMath Unit Types

CompMath Unit Overloaded Operators

CompMath Unit Overloaded Functions


CompMath Unit Types and Overloaded Operators
CompMath Unit Types

Targets: MS-DOS, OS/2, Win32

CompMath Unit

Following types are defined in the CompMath unit:

type

  CReal = Extended;

type Complex = record

  re, im: CReal

end;

type

  TComplex = Complex;

The Complex type describes a record that stores two fields of type CReal (see above), one that represents the real part of a complex number and one that represents the imaginary part.


CompMath Unit Overloaded Operators

Targets: MS-DOS, OS/2, Win32

CompMath Unit

The CompMath unit overloads the following,

arithmetic operators:

+, -, *, /, +:=, -:=, *:=, /:=

relational operators:

=, <>


CompMath Unit Overloaded Functions

Targets: MS-DOS, OS/2, Win32

CompMath Unit

The CompMath unit defines the following functions:

function Abs(const a: Complex): CReal;

function ArcCos(const a: Complex): Complex;

function ArcCosH(const a: Complex): Complex;

function ArcSin(const a: Complex): Complex;

function ArcSinH(const a: Complex): Complex;

function ArcTan(const a: Complex): Complex;

function ArcTanH(const a: Complex): Complex;

function Arg(const a: Complex): CReal;

function Conj(const z: Complex): Complex

function Cos(const a: Complex): Complex;

function CosH(const a: Complex): Complex;

function Cotan(const a: Complex): Complex;

function CotanH(const a: Complex): Complex;

function Exp(const a: Complex): Complex;

function Ln(const a: Complex): Complex;

function Polar(const rho: CReal; const theta: CReal): Complex;

function Power(const a: Complex; const b: CReal): Complex;

function Power(const a: CReal; const b: Complex): Complex;

function Power(const a: Complex; const b: Complex): Complex;

function Sin(const a: Complex): Complex;

function SinH(const a: Complex): Complex;

function Sqr(const a: Complex): Complex;

function Sqrt(const a: Complex): Complex;

function Tan(const a: Complex): Complex;

function TanH(const a: Complex): Complex;


The CRT Unit

The CRT unit contains routines to control the keyboard and monitor. This unit, with over 20 functions and procedures, allows for a powerful interface to be developed between the program and the user. To the end user, a program's appearance and interface are essential aspects that cannot be ignored. With CRT, programming window displays and keyboard handling is a breeze. In the initialization code for CRT, output to the monitor or screen is redirected from the console standard input and output files to the direct screen I/O. Redirection is possible only if the Input and Output file are assigned and reopened.

CRT Unit Variables

CRT Unit Procedures and Functions


CRT Unit Variables
CRT Unit Constants and Variables

Color Constants

TextMode Constants

CheckBreak

CheckEOF

DirectVideo

CheckSnow

LastMode

TextAttr

WindMax

WindMin


Color constants

CRT Unit

Use these color constants with TextColor and TextBackGround procedures.

Dark colors (foreground & background):

Black                         0

Blue                          1

Green                         2

Cyan                          3

Red                           4

Magenta                       5

Brown                         6

LightGray                     7

Light colors (foreground only):

DarkGray                      8

LightBlue                     9

LightGreen                    10

LightCyan                     11

LightRed                      12

LightMagenta                  13

Yellow                        14

White                         15

For flashing (blinking) text foreground, Blink = 128.


TextMode constants

CRT Unit

Use these constants with TextMode procedure.

Value        Meaning

BW40            $00;

CO40            $01;

BW80            $02;

CO80            $03;

Mono            $07;

Font8x8         $FF;


CheckBreak variable

CRT Unit

Controls user termination of an application using the CRT window.

Declaration:

const CheckBreak: Boolean = TRUE;

Remarks:

When CheckBreak is True, the user can terminate the application at any time by pressing Ctrl-Break or Ctrl+C.

Application can not be terminated if CheckBreak is False.


CheckEOF variable

CRT Unit

Controls the end-of-file character checking in the CRT window.

Declaration:

const CheckEOF: Boolean = FALSE;


DirectVideo variable

CRT Unit

Enables and disables direct memory access for Write and WriteLn statements that output to the screen.

Declaration:

const DirectVideo: Boolean = TRUE;

If DirectVideo is TRUE, Write and WriteLn procedures will store characters directly in the video memory, instead of using the BIOS to display them.


CheckSnow variable

CRT Unit

Enables and disables "snow-checking" when storing characters directly in video memory

Declaration:

const CheckSnow: Boolean = FALSE;


LastMode variable

CRT Unit

Each time TextMode is called, the current video mode is stored in LastMode.

Declaration:

var LastMode: Word;

Remarks:

Also, LastMode is initialized at program startup to the then-active video mode.


TextAttr variable

CRT Unit

Stores currently selected text attributes.

Declaration:

var TextAttr: Byte := LigthGray;

Remarks:

The text attributes are normally set through calls to TextColor and TextBackGround.


WindMax variable

CRT Unit

Stores the screen coordinates of the current window.

Declaration:

var WindMax: Word;

Remarks:

These variables are set by calls to the Window procedure. WindMinVAR defines the upper left corner. WindMax defines the lower right corner.

The X coordinate is stored in the low byte, and the Y coordinate is stored in the high byte.

For example, Lo(WindMin) produces the X coordinate of the left edge, and Hi(WindMax) produces the Y coordinate of the bottom edge.

The screen's upper left corner corresponds to (X,Y) = (0,0), but for coordinates sent to Window and GotoXY, the upper left corner is at (1,1).


WindMin variable

CRT Unit

Stores the screen coordinates of the current window.

Declaration:

var WindMin: Word;

Remarks:

These variables are set by calls to the Window procedure. WindMin defines the upper left corner. WindMax defines the lower right corner.

The X coordinate is stored in the low byte, and the Y coordinate is stored in the high byte.

For example, Lo(WindMin) produces the X coordinate of the left edge, and Hi(WindMax) produces the Y coordinate of the bottom edge.

The screen's upper left corner corresponds to (X,Y) = (0,0), but for coordinates sent to Window and GotoXY, the upper left corner is at (1,1).


CRT Unit Procedures and Functions

AssignCrt

ClrEOL

ClrScr

Delay

DelLine

GetCharXY

GotoXY

HideCursor

HighVideo

InsLine

KeyPressed

LowVideo

NormVideo

NoSound

ReadKey

SetScreenSize

ShowCursor

Sound

TextBackGround

TextColor

TextMode

WhereX

WhereY

Window

WriteAttr


AssignCrt procedure

CRT Unit

Associates a text file with the CRT window.

Declaration:

procedure AssignCrt(var f: Text);

Remarks:

AssignCrt works exactly like the Assign standard procedure; however, no file name is specified. Instead, the text file is associated with the CRT.

This allows for faster output (and input) than would normally be possible using standard output (or input) procedure.


ClrEOL procedure

CRT Unit

Associates a text file with the CRT window.

Clears all characters from the cursor position to the end of the line without moving the cursor from it's initial position.

Declaration:

procedure ClrEOL;

Remarks:

All character positions are set to blanks with the currently defined text attributes. Thus, if TextBackground is not black, the current cursor position to the right edge becomes the background color.

ClrEol is window-relative.


ClrScr procedure

CRT Unit

Clears the active windows and returns the cursor to the upper-left corner.

Declaration:

procedure ClrScr;

Remarks:

Sets all character positions to blanks with the currently defined text attributes. Thus, if TextBackground is not black, the entire screen becomes the background color. This also applies to characters cleared by ClrEOL, InsLine and DelLine, and to empty lines created by scrolling.

ClrScr is window-relative.


Delay procedure

CRT Unit

Delays a specified number of milliseconds.

Declaration:

procedure Delay(Ms: Word);

Remarks:

Ms specifies the time, in milliseconds of the delay.

Delay is only an approximation, and therefore, the delay period will not last for the exact number of Ms milliseconds.


DelLine procedure

CRT Unit

Deletes the line containing the cursor.

Declaration:

procedure DelLine;

Remarks:

The line containing the cursor is deleted, and all lines below are shifted by one line. A new line is then added at the bottom.

All character positions are set to blanks using the currently defined text attributes. Thus, if the TextBackground is not black, the new line becomes the background color.


GetCharXY function

CRT Unit

Reads a character from the screen.

Declaration:

function GetCharXY(X, Y: Longint): Char;


GotoXY procedure

CRT Unit

Shifts the cursor over to the given coordinates within the virtual screen.

Declaration:

procedure GotoXY(X, Y: Byte);

Remarks:

The upper-left corner of the virtual screen corresponds to (1, 1).


HideCursor procedure

CRT Unit

Hides the text cursor.

Declaration:

procedure HideCursor;

See also: ShowCursor


HighVideo procedure

CRT Unit

Selects high-intensity characters.

Declaration:

procedure HighVideo;

Remarks:

HighVideo sets the high intensity bit of TextAttr’s fore-ground color, thus mapping colors 0-7 onto colors 8-15.


InsLine procedure

CRT Unit

Inserts an empty line at the cursor position.

Declaration:

procedure InsLine;

Remarks:

All lines below the inserted line are moved down one line, and the bottom line is scrolled off of the screen.

All character positions are set to blanks with the currently defined text attributes; therefore, if the TextBackground is not black, the new line will become the background color.


KeyPressed function

CRT Unit

Returns True if a key has been pressed on the keyboard.

Declaration:

function KeyPressed: Boolean;

Remarks:

The key code can be read using the ReadKey function.


LowVideo procedure

CRT Unit

Selects low intensity characters.

Declaration:

procedure LowVideo;

Remarks:

LowVideo clears the high-intensity bit of TextAttr’s foreground color, thus mapping colors 8 to 15 onto colors 0 to 7.


NormVideo procedure

CRT Unit

Selects the original text attribute read from the cursor location at startup.

Declaration:

procedure NormVideo;

Remarks:

NormVideo restores TextAttr to the value it had when the program was started.


NoSound procedure

CRT Unit

Turns off the computer's internal speaker.

Declaration:

procedure NoSound;


ReadKey function

CRT Unit

Reads a character or an extended scan code from the keyboard.

Declaration:

function ReadKey: Char;

Remarks:

The character is not echoed to the screen.


SetScreenSize procedure

CRT Unit

Defines the custom size in characters of the text screen.

Declaration:

procedure SetScreenSize(Cols, Rows: DWord);


ShowCursor procedure

CRT Unit

Shows the text cursor.

Declaration:

procedure ShowCursor;

See also: HideCursor


Sound procedure

CRT Unit

Starts the internal speaker.

Declaration:

procedure Sound(Hz: DWord);

Remarks:

Hz specifies the frequency of the emitted sound in hertz. The sound continues until explicitly turned off by a call to NoSound.


TextBackGround procedure

CRT Unit

Selects the background color.

Declaration:

procedure TextBackground(Color: Byte);

Remarks:

Color is an integer expression in the range 0..7, corresponding to one of the first eight text color constants. TextBackground sets bits 4-6 of TextAttr to Color.

The background of all characters subsequently written will be in the specified color.

See also: Color Constants


TextColor procedure

CRT Unit

Selects the foreground character color.

Declaration:

procedure TextColor(Color: Byte);

Remarks:

Color is an integer expression in the range 0..15, corresponding to one of the text color constants defined in CRT.

TextColor sets bits 0-3 to Color. If Color is greater than 15, the blink bit (bit 7) is also set; otherwise, it is cleared.

See also: Color Constants


TextMode procedure

CRT Unit

Selects a specific text mode.

Declaration:

procedure TextMode(Mode: Integer);

Remarks:

When TextMode is called, the current window is reset to the entire screen, DirectVideo is set to True, CheckSnow is set to True if a color mode was selected, the current text attribute is reset to normal corresponding to a call to NormVideo, and the current video is stored in LastMode. In addition, LastMode is initialized at program startup to the then-active video mode.

Specifying TextMode(LastMode) causes the last active text mode to be re-selected. This is useful when you want to return to text mode after using a graphics package, such as Graph unit.

See also: TextMode Constants


WhereX function

CRT Unit

Returns the CP's X coordinate of the current cursor location.

Declaration:

function WhereX: Byte;


WhereY function

CRT Unit

Returns the CP's Y coordinate of the current cursor location.

Declaration:

function WhereY: Byte;


Window procedure

CRT Unit

Defines a text window on the screen.

Declaration:

procedure Window(X1, Y1, X2, Y2: Byte);

Remarks:

X1 and Y1 are the coordinates of the upper left corner of the window, and X2 and Y2 are the coordinates of the lower right corner. The upper left corner of the screen corresponds to (1, 1). The minimum size of a text window is one column by one line. If the coordinates are invalid in any way, the call to Window is ignored.

The default window is (1, 1, 80, 25) in 25-line mode, and (1, 1, 80, 43) in 43-line mode, corresponding to the entire screen.

All screen coordinates (except the window coordinates themselves) are relative to the current window. For instance, GotoXY(1, 1) will always position the cursor in the upper left hand corner of the current window.

Many CRT procedures and functions are window-relative, including ClrEOL, ClrScr, DelLine, GotoXY, InsLine, WhereX, WhereY, Write and Writeln.

WindMin and WindMax store the current window definition. A call to the Window procedure always moves the cursor to (1, 1).


WriteAttr procedure

CRT Unit

Writes given string S in attributes/characters format to the screen at (X,Y).

Declaration:

procedure WriteAttr(X, Y: Longint; Var S; Len: Longint);


The Debug Unit

This module prints out the error code and the call stack in case of a run-time error. The stack is printed as follows:

 RunError #201 (range check error)

 Calls stack:

 SYSTEM.BOUND_ERROR [chk_fun.inp(21) at 0000000A]

 TEST.ASSN [TEST.PAS(61) at 00000015]

 TEST.TEST [TEST.PAS(82) at 0000001D]

To use Debug, simply list it in the uses clause of the main program. Using the Debug unit increases the .EXE module size

 A call of a procedure with a NIL address is currently diagnosed as an arithmetic overflow, or (under the PMODE extender) causes a GP Fault or other traps.


The DOS Unit

The Dos unit allows easy access to most of the functions provided by the MS-DOS operating system from 32-bit protected mode application. Operations such as find file, disk size or status, time and date, get environment strings, and more are provided by the Dos unit. In total, over 50 functions and procedures are available. For more information about MS-DOS consult your DOS operating system reference

manual.

Dos Unit Constants and Variables

Dos Unit Procedures and Functions


Dos Unit Constants and Variables

Flag constants

File-mode constants

File-attribute constants

DataTime type

DosError variable

Registers type

SearchRec type


Flag constants

Dos Unit, WinDos Unit

The Flag constants (fXXXX) test individual flag bits in the Flags register after a call to Intr or MsDos.

Constant    Value

fCarry      $0001

fParity     $0004

fAuxiliary  $0010

fZero       $0040

fSign       $0080

fOverflow   $0800


File-mode constants

Dos Unit, WinDos Unit

File-handling procedures use fmXXXX constants when opening and closing disk files.

The Mode fields of TFileRec and TTextRec will contain one of these values:

Constant  Value

fmClosed  $D7B0

fmInput   $D7B1

fmOutput  $D7B2

fmInOut   $D7B3


File-attribute constants

Dos Unit, WinDos Unit

These constants test, set, and clear file-attribute bits in connection with the GetFAttr, SetFAttr, FindFirst, and FindNext procedures.

These constants are additive. The faAnyFile constant is the sum of all attributes.

Constant     Value

ReadOnly     $01

Hidden       $02

SysFile      $04

VolumeID     $08

Directory    $10

Archive      $20

AnyFile      $3F


DataTime type

Dos Unit

The UnpackTime and PackTime procedures use variables of type DateTime to examine and construct 4-byte, packed date-and-time values for the GetFTime, SetFTime, FindFirst, and FindNext procedures:

Declaration:

type

  DateTime = record

    Year, Month, Day, Hour,

    Min, Sec: Word;

  end;


DosError variable

Dos Unit, WinDos Unit

DosError is used by many of the routines in the Dos unit to report errors.

Declaration:

var DosError: Integer;

Remarks:

The values stored in DosError are operating system depended error codes.


Registers type

Dos Unit

The Intr and MsDos procedures use variables of type Registers to specify the input register contents and examine the output register contents of a software interrupt.

Declaration:

type Registers =

  record

  case Integer of

    1: (edi, esi, ebp, _res, ebx, edx, ecx, eax: Longint;

        flags, es, ds, fs, gs, ip, cs, sp, ss: Word);

    2: (_dmy2: array [0..15] of byte; bl, bh, b1, b2, dl,

        dh, d1, d2, cl, ch, c1, c2, al, ah: Byte);

    3: (di, i1, si, i2, bp, i3, i4, i5, bx, b3, dx, d3, cx,

        c3, ax: Word);

  end;


SearchRec type

Dos Unit

The FindFirst and FindNext procedures use variables of type SearchRec to scan directories:

Declaration:

type

  SearchRec = record

    Fill : array[1..21] of Byte;

    Attr : Byte;

    Time : Longint;

    Size : Longint;

    Name : string[12];

end;

Information for each file found by FindFirst or FindNext is reported back in a SearchRec.

Field    Meaning

Attr     File's attributes

Time     File's packed date and time

Size     File's size, in bytes

Name     File's name

The Fill field is reserved by DOS and should never be modified.


Dos Unit Procedures and Functions

DiskFree

DiskSize

DosExitCode

DosVersion

EnvCount

EnvStr

Exec

FExpand

FindFirst

FindNext

FSearch

FSplit

GetCBreak

GetDate

GetEnv

GetFAttr

GetFTime

GetIntVec

GetTime

GetVerify

Intr

Keep

MsDos

PackTime

SetCBreak

SetDate

SetFAttr

SetFTime

SetIntVec

SetTime

SetVerify

SwapVectors

UnpackTime


DiskFree function

Dos Unit, WinDos Unit

Returns the number of free bytes on a specified disk drive.

Declaration:

function DiskFree(Drive: Byte): Longint;

Remarks:

Drive is the drive to check where A = 1, B = 2, and so on. If Drive is zero then the current drive is used.

DiskFree is useful in determining whether there is enough disk space for disk output. A message can be displayed if there is not enough disk space available.

Example:

uses Dos;

begin

  if (DiskFree(0) < 100000) and IsFixed(0) then

  begin

    WriteLn('Insufficient Disk Space');

    Halt(1);

  end;

  ...

end.

See also:

DiskSize


DiskSize function

Dos Unit, WinDos Unit

Returns the total size, in bytes, of a specified disk drive.

Declaration:

function DiskSize(Drive: Byte): Longint;

Drive is the drive to check where A = 1, B = 2, and so on. If Drive is zero then the current drive is used.

Example:

size := DiskSize(0);  // size of current drive

size := DiskSize(3);  // size of drive C:

See also:

DiskFree


DosExitCode function

Dos Unit

Returns the exit code of a subprocess.

Declaration:

function DosExitCode: Word;

See also:

Exec


DosVersion function

Dos Unit, WinDos Unit

Returns the OS version number.

Declaration:

function DosVersion: Word;


EnvCount function

Dos Unit

Returns the number of strings contained in the system environment.

Declaration:

function EnvCount: Integer;

See also:

EnvStr

GetEnv


EnvStr function

Dos Unit

Returns a specified environment string.

Declaration:

function EnvStr(Index: Integer): string;

Remarks:

Index is the number of the environment variable, for instance, the first variable is one, second is two, and so on. An invalid index returns an empty string.

EnvStr returns a string in the form of (VarName=String). If the order of system environment variables is unknown then use GetEnvto retrieve a variable by name.

Example:

uses Dos;

var

  i : Integer;

begin

  for i := 1 to EnvCount do

    WriteLn(EnvStr(i));

end.

See also:

EnvCount

GetEnv


Exec procedure

Dos Unit

Executes a specified program with a specified command line.

Declaration:

procedure Exec(Path, CmdLine: string);

Remarks:

Path is the drive, directory, and program name to execute. CmdLine contains the command line arguments.

Exec transfers control to the program specified by Path. Memory allocation is not modified by Exec. Upon completion of Exec use DosExitCode to determine the exit code of the program. Exec also sets the value of DosError if an error occurred.

Exec does not execute programs that require File Control Blocks (FCBs).

Example:

begin

  Exec('PROGRAM.EXE','');

  WriteLn(Hi(DosExitCode),'.', Lo(DosExitCode),'.',DosError);

end.

See also:

DosExitCode


FExpand function

Dos Unit

Expands a file name into a fully-qualified file name.

Declaration:

function FExpand(Path: PathStr): PathStr;


FindFirst procedure

Dos Unit, WinDos Unit

Searches the specified directory for the matching file.

Declaration:

procedure FindFirst(Path: PChar; Attr: Word; var F: TSearchRec);

Remarks:

Path is the drive and directory to search in and the file name to search for. Wildcards are allowed, for instance, 'MYFILE??.*'.

Attr contains the file attributes to include in the search in addition to all normal files.

FindFirst is used in conjunction with FindNext. Use FindNext to locate any addition files matching the search criteria. All errors are reported in DosError , which is a variable defined in the Dos unit.

See also:

FSearch

Example:

program DirList;

uses Dos;

var

  TotalDirCnt: Longint;

procedure List(Path : String);

var

  DirSearchRec: SearchRec;

begin

  if (Path[Length(Path)] <> '\') then Path := Path + '\';

  FindFirst(Path + '*.*', AnyFile, DirSearchRec);

  while DosError = 0 do

  begin

    if (DirSearchRec.Name <> '.') and (DirSearchRec.Name <> '..') and

       ((DirSearchRec.Attr and Directory) <> 0)

    then

    begin

      Inc(TotalDirCnt);

      Writeln(Path + DirSearchRec.Name);

      List(Path + DirSearchRec.Name);

    end;

    FindNext(DirSearchRec) ;

  end;

end;

begin

  TotalDirCnt := 0;

  List('C:\');

  Writeln;

  Writeln('Total number of directories = ', TotalDirCnt);

end.


FindNext procedure

Dos Unit, WinDos Unit

Finds the next entry that matches the name and attributes specified in an earlier call to FindFirst.

Declaration:

procedure FindNext(var F: TSearchRec);

Remarks:

FindNext is used in conjunction with FindFirst. Use FindNext to locate any addition files matching the search criteria defined by a prior call to FindFirst. F must be the same variable that was passed to FindFirst. All errors are reported in DosError, which is a variable defined in the Dos unit.

Example:

uses Dos;

var

  DirRec : SearchRec;

begin

  FindFirst('C:/*.*',AnyFile,DirRec);

  while DosError = 0 do

    WriteLn(DirRec.Name);

    FindNext(DirRec);

  end;

end.

See also:

FSearch


FSearch function

Dos Unit

Searches for a file.

Declaration:

function FSearch(Path: PathStr; DirList: string): PathStr;

Remarks:

Path is of type PathStr which is defined in the Dos unit. DirList is a list of the directories to include in the search each delimited with a semicolon (;).

FSearch returns the directory and file name if the file has been located. If Path is not found then an empty string is returned. FSearch always begins with the current directory and then checks the directories listed in DirList in the order that they appear.

Example:

uses Dos,Strings;

var

  DosPath,

  TreePath: String;

  File    : PathStr;

begin

  DosPath := GetPath;

  File    := 'TREE.COM';

  TreePath:= FSearch(File, DosPath);

  if Empty(TreePath) then Halt(1);

  TreePath := AppendBKSlash(TreePath);

  Exec(TreePath + File,'');

end.

See also:

FindFirst

FExpand

FSplit


FSplit procedure

Dos Unit

Splits a file name into its three components.

Declaration:

procedure FSplit(Path: PathStr; var Dir: DirStr; var Name: NameStr; var Ext: ExtStr);

Remarks:

Use this procedure to break down a file specification into three parts: path, file name, and file extension. Path is of type PathStr which is defined in the Dos unit. Dir returns the path or directory part of Path. Name returns the actual file name without extension. Ext returns the file extension preceded by a period (.).

It is possible that one or more of the components be returned  empty. This occurs if Path contains no such component. For instance, if there is no path, Dir is empty.

Example:

uses Dos;

var

  Fi    : File;

  Direc : DirStr;

  Fname : NameStr;

  Exten : ExtStr;

begin

  FSplit(ParamStr(1), Direc, Fname, Exten);

  if Fname = '' then Halt(1);

  Assign(Fi, ParamStr(1));

  Erase(Fi);

end.


GetCBreak procedure

Dos Unit, WinDos Unit

Returns the state of Ctrl-Break checking in DOS.

Declaration:

procedure GetCBreak(var Break: Boolean);

Remarks:

State returns True if Ctrl-Break is enabled, otherwise False.

With Ctrl-Break checking enabled, all I/O calls (console, printer, and communications) are checked. To set Ctrl-Break either on or off, use SetCBreak.


GetDate procedure

Dos Unit, WinDos Unit

Returns the current date set in the operating system.

Declaration:

procedure GetDate(var Year, Month, Day, DayOfWeek: Word);


GetEnv function

Dos Unit

Returns the value of a specified environment variable.

Declaration:

function GetEnv(VarName: string): string;

Remarks:

VarName is the name of the variable to retrieve. If VarName does not exist as an environment variable then an empty string is returned.

GetEnv returns the string assigned to the environment variable.

Example:

s := GetEnv('COMSPEC');  // Returns COMSPEC


GetFAttr procedure

Dos Unit, WinDos Unit

Returns the attributes of a file.

Declaration:

procedure GetFAttr(var F; var Attr: Word);

Remarks:

F is a file variable, either typed, untyped, or text file that is not open. Attr contains the file attributes.

The file associated with F must be closed. Attr should be examined by ANDing it with the file attribute constants, which are defined in the Dos unit.

Errors are reported in DosError , a variable defined in the Dos unit. For more information about file attributes consult your DOS reference manual.

Example:

uses Dos;

var

  Fi  : Text;

  Attr: Word;

begin

  Assign(Fi,'THEFILE.DOC');

  GetFAttr(Fi, Attr);

  if (Attr and ReadOnly) <> 0 then SetFAttr(Fi,(Attr xor ReadOnly));

end.

See also:

SetFAttr


GetFTime procedure

Dos Unit, WinDos Unit

Returns the date and time a file was last written.

Declaration:

procedure GetFTime(var F; var Time: Longint);

Remarks:

The file associated with F must be open. Time can be unpacked with UnPackTime. Errors are reported in DosError, a variable defined in the Dos unit.

Example:

uses Dos;

var

  Fi  : Text;

  Time: Longint;

  DT  : DateTime;

begin

  Assign(Fi, 'DATA.BAK');

  Reset(Fi);

  GetFTime(Fi, Time);

  UnPackTime(Time, DT);

  WriteLn('Year:   ', DT.Year);

  WriteLn('Month:  ', DT.Month);

  WriteLn('Date:   ', DT.Day);

  Close(Fi);

end.

See also:

SetFTime


GetIntVec procedure

Dos Unit, WinDos Unit

Returns the address stored in a specified interrupt vector.

Declaration:

procedure GetIntVec(IntNo: Byte; var Vector: Pointer);

procedure GetIntVec(IntNo: Byte; var Vector: FarPointer);

Remarks:

Note that GetIntVec returns the address of a protected mode interrupt. To get the vector of a real mode interrupt use GetRealIntVec. Interrupts  may occur while in protected mode or while in real mode.

See also:

SetIntVec

FarPointer


GetTime procedure

Dos Unit, WinDos Unit

Returns the current time set in the operating system.

Declaration:

procedure GetTime(var Hour, Minute, Second, Sec100: Word);

Remarks:

Ranges of the values returned are Hour [0..23], Minute [0..59], Second [0..59], and Sec100 (hundredths of seconds) [0..99].

Example:

var

  Hour, Minute, Second, Sec100: Word;

begin

  GetTime(Hour, Minute, Second,Sec100);

  WriteLn('Current time is: ', Hour, ':', Minute, ':', Second, ':', Sec100);

end.

See also:

SetTime


GetVerify procedure

Dos Unit, WinDos Unit

Returns the state of the verify flag in DOS.

Declaration:

procedure GetVerify(var State: Boolean);

Remarks:

State is True if the DOS verify flag is enabled, otherwise false.

With the DOS verify flag enabled, all output to disk is verified to ensure data integrity. Otherwise, all output is not verified. To set the status of the DOS verify flag, use SetVerify.


Intr procedure

Dos Unit, WinDos Unit

Executes a specified software interrupt.

Declaration:

procedure Intr(IntNo: Byte; var Regs: TRegisters);

Remarks:

Before calling Intr, load Regs with the appropriate parameters needed for the interrupt. Regs returns the values of the registers after the interrupt call. Calls that depend on ESP and SS cannot be executed. For more information about software interrupt calls consult your BIOS and DOS reference manual.

Note that all segment resgisters (DS,ES,FS,GS) must contain valid segment descriptors  or be set to zero prior to calling Intr. All interrupt calls that require an offset must be passed a 32 bit offset.

Example:

uses Dos;

function GetVideoMode: Byte;

var

  Regs: Registers;

begin

  Regs.AX := $0F00;

  Regs.DS := DSeg;  Regs.ES := 0;

  Regs.FS := 0;     Regs.GS := 0;

  Intr($10, Regs);

  GetVideoMode := Regs.Al;

end.


Keep procedure

Dos Unit

This procedure is only stub and always causes run-error message.

Declaration:

procedure Keep(ExitCode: Word);


MsDos procedure

Dos Unit, WinDos Unit

Executes a DOS function call.

Declaration:

procedure MsDos(var Regs: TRegisters);

Remarks:

Load Regs with the proper parameters before calling MS-DOS. Regs returns the values of the registers after the interrupt. Notice that TRegisters type allows access to 32 bit registers. Calls to DOS that depend on ESP and SS cannot be executed. To an interrupt other than $21, use Intr. For more information about DOS interrupt calls consult your DOS reference manual.

Note that all segment registers (DS, ES, FS, GS) must contain valid segment descriptors or be set to zero prior to using MS-DOS.

Example:

uses Dos;

procedure DispString(DispStr: String);

var

  Regs    : Registers;

begin

  DispStr := DispStr + #0;

  Regs.AX := $0900;

  Regs.EDX:= DWord(@DispStr) + 1;

  Regs.DS := DSeg;

  Regs.ES := 0;

  Regs.FS := 0;

  Regs.GS := 0;

  MsDos(Regs);

end.


PackTime procedure

Dos Unit, WinDos Unit

Converts a DateTime record.

Declaration:

procedure PackTime(var T: DateTime; var Time: Longint);

Remarks:

PackTime can be used in conjunction with SetFTime. To unpack a four byte packed date time into a DateTime record, use UnpackTime.


SetCBreak procedure

Dos Unit, WinDos Unit

Sets the state of Ctrl-Break checking.

Declaration:

procedure SetCBreak(Break: Boolean);

Remarks:

With Ctrl-Break checking enabled, all I/O calls (console, printer, and communications) are checked. To get Ctrl-Break status, use GetCBreak.


SetDate procedure

Dos Unit, WinDos Unit

Sets the current date in the operating system.

Declaration:

procedure SetDate(Year, Month, Day: Word);

Remarks:

Invalid dates are ignored by the operating system. To get the operating system date use GetDate.


SetFAttr procedure

Dos Unit, WinDos Unit

Sets the attributes of a file.

Declaration:

procedure SetFAttr(var F; Attr: Word);

Remarks:

The file associated with F must be closed. Attr should be formed by ORing it with the file attribute constants which

are defined in the Dos unit.

Errors are reported in DosError, a variable defined in the Dos unit. For more information about file attributes consult your DOS reference manual.

Example:

uses Dos;

var

  Fi  : File;

  Attr: Word;

begin

  Assign(Fi, 'SECRET.DOC');

  Attr := Hidden or ReadOnly;

  SetFAttr(Fi, Attr);

  WriteLn('SECRET.DOC is now hidden.');

end.

See also:

GetFAttr


SetFTime procedure

Dos Unit, WinDos Unit

Sets the date and time a file was last written.

Declaration:

procedure SetFTime(var F; Time: Longint);

The file associated with F must be open. A packed date and time stamp can be created with PackTime. Errors are reported in DosError, a variable defined in the Dos unit. For more information about a file's packed date and time stamp consult your DOS reference manual.

Example:

uses Dos;

var

  Fi  : Text;

  DT  : DateTime;

  Time: Longint;

begin

  Assign(Fi, 'FUTURE.DOC');

  Reset(Fi);

  with DT do begin

    Year  := 2010;

    Month := 3;

    Day   := 31;

    Hour  := 2;

    Min   := 45;

    Sec   := 22;

  end;

  PackTime(DT, Time);

  SetFTime(Fi, Time);

  Close(Fi);

end.


SetIntVec procedure

Dos Unit, WinDos Unit

Sets a specified interrupt vector to a specified address.

Declaration:

procedure SetIntVec(IntNo: Byte; Vector: Pointer);

procedure SetIntVec(IntNo: Byte; Vector: FarPointer);

Remarks:

Interrupts may occur while in protected mode or while in real mode.

Example:

program Timer;

uses Dos, Crt;

var  Int1CSave: FarPointer;

     Time     : LongInt;

// timer handler

procedure TimerHandler(eip,eax,ecx,edx,ebx,esp,ebp,esi,edi: Dword; gs,fs,es: Word); interrupt;

var StoreX, StoreY: Word;

begin

  Inc(time);

  Store X:= WhereX;

  Store Y:= WhereY;

  GotoXY(1,1);

  Write(time);

  GotoXY(StoreX, StoreY);

  Port[$20] := $20;

end;

// main program

begin

  ClrScr;

  Time := 0;

  GetIntVec($1C, Int1CSave);

  SetIntVec($1C, @TimerHandler);

  Writeln;

  Writeln('Type something and press "ENTER" to exit');

  Readln;

  SetIntVec($1C, Int1CSave);

end.

See also:

GetIntVec

FarPointer


SetTime procedure

Dos Unit, WinDos Unit

Sets the current time in the operating system.

Declaration:

procedure SetTime(Hour, Minute, Second, Sec100: Word);

Remarks:

Invalid values are ignored. To get the current operating system time use GetTime.


SetVerify procedure

Dos Unit, WinDos Unit

Sets the state of the verify flag in DOS.

Declaration:

procedure SetVerify(Verify: Boolean);

See also:

GetVerify


SwapVectors procedure

Dos Unit

The SwapVectors function does nothing and provided for compatibility with Borland Pascal.

Declaration:

procedure SwapVectors;


UnpackTime procedure

Dos Unit, WinDos Unit

Converts a Longint to a record.

Declaration:

procedure UnpackTime(Time: Longint; var DataTime: TDateTime);

Remarks:

UnPackTime can be used in conjunction with GetTime, FindFirst, and FindNext. These routines return a file's four byte packed date and time stamp. To pack a DateTime record, use PackTime.

Example:

uses Dos;

var

  Fi  : Text;

  Time: Longint;

  DT  : DateTime;

begin

  Assign(Fi,'USER.DOC');

  Reset(Fi);

  GetFTime(Fi,Time);

  UnPackTime(Time,DT);

  WriteLn('Year:   ',DT.Year);

  WriteLn('Month:  ',DT.Month);

  WriteLn('Date:   ',DT.Day);

  Close(Fi);

end.


The DPMI Unit

  The DOS  Protected Mode Interface (DPMI) was defined to allow DOS programs to access the extended memory of PC architecture computers while maintaining system protection. DPMI defines a specific subset of DOS and BIOS calls that can be made by protected mode DOS programs. It also defines a new interface via software interrupt 31h that protected mode  programs use to allocate memory, modify descriptors, call real mode  software, etc. Any operating system that currently supports virtual  DOS sessions should be capable of supporting DPMI without affecting system security. Some DPMI implementations can execute multiple protected mode programs in independent virtual machines. Thus, DPMI applications can behave exactly like any other standard DOS program and can, for example, run in the background or in a window (if the environment supports these features). Programs that run in protected mode also gain all the benefits of virtual memory and can run in 32-bit flat model if desired. The DPMI unit intended for simplification access to DPMI functions from Pascal program.

DPMI Unit Types

DPMI Unit Procedures and Functions


DPMI Unit Types

TRmRegs type

TDescriptor type


TDescriptor type

DPMI Unit

Declaration:

type

  TDescriptor = record

  SegmentLimit: Word;

  BaseAddressL: Word;

  BaseAddressH: Byte;

  FlagsL:       Byte;

  FlagsH:       Byte;

  BaseAddressU: Byte;

end;


TRmRegs type

DPMI Unit

Declaration:

type

  TRmRegs = record

   case integer of

     1: (edi,esi,ebp,_res,ebx,edx,ecx,eax: Longint;

         flags,es,ds,fs,gs,ip,cs,sp,ss: Word);

     2: (_dmy2: array [0..15] of byte; bl,bh,b1,b2,dl,dh,d1,d2,cl,

     3: (di,i1,si,i2,bp,i3,i4,i5,bx,b3,dx,d3,cx,c3,ax:  Word);

end;


DPMI Unit Procedures and Functions

AllocateDescriptors

AllocDosMemoryBlock

AllocRealModeCallBack

AllocateSpecificDescriptor

CallRealModeFar

CallRealModeIRet

ClearRmRegs

CreateCodeAlias

CreateCodeDescriptor

CreateDataAlias

CreateDataDescriptor

DosMemoryAlloc

DosMemoryFree

FarGetByte

FarGetDWord

FarGetWord

FarPutByte

FarPutDWord

FarPutWord

FreeDescriptor

FreeDosMemoryBlock

FreePhysicalMap

FreeRealModeCallBack

GetCS

GetDisableInterruptState

GetDPMIIntVec

GetDPMIVer

GetDS

GetEnableInterruptState

GetExceptionHandler

GetFreeMemoryInfo

GetInterruptState

GetRealModeIntVec

GetSegmentBaseAddress

GetSelectorAccessRights

MapPhysicalToLinear

RealModeInt

ResizeDosMemoryBlock

SegmentToDescriptors

SelectorInc

SetDPMIIntVec

SetExceptionHandler

SetRealModeIntVec

SetSelectorAccessRights

SetSelectorBaseAddress

SetSelectorLimit


AllocateDescriptors function

DPMI Unit

This function is used to allocate one or more descriptors from the task's Local Descriptor Table (LDT). The descriptor(s) allocated must be initialized by the application.

Declaration:

function AllocateDescriptors(NumberOfDescriptors: Word): Word;

Remarks:

Returns base selector if successful or zero if failed.

See also:

FreeDescriptor


AllocDosMemoryBlock function

DPMI Unit

This function will allocate a block of memory from the DOS free memory pool. It returns both the real mode segment and one or more descriptors that can be used by protected mode applications to access the block.

Declaration:

function AllocDOSmemoryBlock(SizeInBytes: DWord): DWord;

Remarks:

Returns paragraph-segment value in its high-order word and a selector in its low-order word if successful. Otherwise returns zero.

See also:

FreeDosMemoryBlock

ResizeDosMemoryBlock


AllocRealModeCallBack function

DPMI Unit

This function is used to obtain a unique real mode SEG:OFFSET that will transfer control from real mode to a protected mode procedure.

Declaration:

function AllocateRealModeCallBack(HandlerAddr, RegsAddr: Pointer; var HndSeg: Word; var HndOfs: DWord): Boolean;

Remarks:

Returns True if successful.

See also:

FreeRealModeCallBack


AllocateSpecificDescriptor function

DPMI Unit

This function is used to allocate one specific LTD descriptor.

Declaration:

function AllocateSpecificDescriptor(Selector: Word): Boolean;

Remarks:

Returns True if successful.

See also:

FreeDescriptor


CallRealModeFar procedure

DPMI Unit

This function calls a real mode procedure. The called procedure must execute a far return when it completes.

Declaration:

function CallRealModeFar(var Regs: TRmRegs): Boolean;

Remarks:

Returns True if successful.

See also:

TRmRegs type


CallRealModeIRet procedure

DPMI Unit

This function calls a real mode procedure. The called procedure must execute an iret when it completes.

Declaration:

function CallRealModeIRet(var Regs: TRmRegs): Boolean;

Remarks:

Returns True if successful.

See also:

TRmRegs type


ClearRmRegs procedure

DPMI Unit

This procedure clears (fills with zero) the Real Mode registers structure. You must do it before you call any function, which uses it!

Declaration:

procedure ClearRmRegs(var Regs: TRmRegs);

See also:

RealModeInt

TRmRegs type


CreateCodeAlias function

DPMI Unit

This function will create a code descriptor that has the same base and limit as the specified code segment descriptor.

Declaration:

function CreateCodeAlias(Selector: Word): Word;

Remarks:

Returns alias descriptor is successful.


CreateCodeDescriptor function

DPMI Unit

This function is used to allocate one code descriptor from the task's Local Descriptor Table (LDT) with specified Base and Limit.

Declaration:

function CreateCodeDescriptor(Base, Limit: DWord): Word;

Remarks:

Returns code selector if successful. Otherwise returns zero.

See also:

FreeDescriptor


CreateDataAlias function

DPMI Unit

This function will create a code descriptor that has the same base and limit as the specified code segment descriptor.

Declaration:

function CreateDataAlias(Selector: Word): Word;

Remarks:

Returns alias selector is successful. Otherwise returns zero.

See also:

FreeDescriptor


CreateDataDescriptor function

DPMI Unit

This function is used to allocate one data descriptor from the task's Local Descriptor Table (LDT) with specified Base and Limit

Declaration:

function CreateDataDescriptor(Base, Limit: DWord): Word;

Remarks:

Returns data selector if successful, or zero if failed.

See also:

FreeDescriptor


DosMemoryAlloc function

DPMI Unit

This function will allocate a block of memory from the DOS free memory pool. It returns real mode only segment of allocated DOS memory block.

Declaration:

function DOSMemoryAlloc(SizeInBytes: DWord): Word;

Remarks:

Returns segment value if successful. Otherwise returns zero.

To get access to allocated DOS memory block you  should multiply the returned paragraph-segment by 16.

Example:

function MkDOSPointer (Segment: Word): Pointer;

begin

  Result := DWord(Segment)*16;

end.

This function makes a protected mode pointer on a given segment of allocated DOS memory block.

See also:

DosMemoryFree


DosMemoryFree function

DPMI Unit

This function  frees memory that was allocated through the DosMemoryAlloc function.

Declaration:

function DOSMemoryFree(Segment: Word): Boolean;

Remarks:

Returns True if successful.

DOSMemoryAlloc and DOSMemoryFree functions uses Int 21h.

See also:

DosMemoryAlloc


FarGetByte function

DPMI Unit

Returns byte value from specified offset of specified protected mode segment (selector).

Declaration:

function FarGetByte(Seg: Word; Offs: DWord): Byte;

Returns word value from specified offset of specified protected mode segment (selector).

See also:

FarGetDWord

FarGetWord

FarPutByte

FarPutDWord

FarPutWord


FarGetDWord function

DPMI Unit

Returns dword value from specified offset of specified protected mode segment (selector).

Declaration:

function FarGetDWord(Seg: Word; Offs: DWord): DWord;

See also:

FarGetByte

FarGetWord

FarPutByte

FarPutDWord

FarPutWord


FarGetWord function

DPMI Unit

Returns word value from specified offset of specified protected mode segment (selector).

Declaration:

function FarGetWord(Seg: Word; Offs: DWord): Word;

See also:

FarGetByte

FarGetDWord

FarPutByte

FarPutDWord

FarPutWord


FarPutByte procedure

DPMI Unit

Puts byte value to specified offset of specified protected mode segment (selector).

Declaration:

procedure FarPutByte(Seg: Word; Offs: DWord; Value: Byte);

See also:

FarGetByte

FarGetDWord

FarGetWord

FarPutDWord

FarPutWord


FarPutDWord procedure

DPMI Unit

Puts dword value to specified offset of specified protected mode segment (selector).

Declaration:

procedure FarPutDWord(Seg: Word; Offs: DWord; Value: DWord);

See also:

FarGetByte

FarGetDWord

FarGetWord

FarPutByte

FarPutWord


FarPutWord procedure

DPMI Unit

Puts word value to specified offset of specified protected mode segment (selector).

Declaration:

procedure FarPutWord(Seg: Word; Offs: DWord; Value: Word);

See also:

FarGetByte

FarGetDWord

FarGetWord

FarPutByte

FarPutDWord


FreeDescriptor function

DPMI Unit

This function is used to free descriptors that were allocated through the AllocateDescriptors function.

Declaration:

function FreeDescriptor(Selector: Word): Boolean;

Remarks:

Returns True if successful.

See also:

AllocateDescriptors

AllocateSpecificDescriptor

CreateCodeDescriptor

CreateDataDescriptor


FreeDosMemoryBlock function

DPMI Unit

This function frees memory that was allocated through the AllocDosMemoryBlock function.

Declaration:

function FreeDOSMemoryBlock(Selector: Word): Boolean;

Remarks:

Returns True if successful.

See also:

AllocDosMemoryBlock

ResizeDosMemoryBlock


FreePhysicalMap function

DPMI Unit

This function frees physical mapping that was allocated through the MapPhysicalToLinear function.

Declaration:

function FreePhysicalMap(LinearAddr: DWord): Boolean;

Remarks:

Returns True if successful.

See also:

MapPhysicalToLinear


FreeRealModeCallBack function

DPMI Unit

This function frees a real mode call-back address that was allocated through the allocate real mode call-back address service.

Declaration:

function FreeRealModeCallBack(HndSeg: Word; HndOfs: DWord): Boolean;

Remarks:

Returns True if successful.

See also:

AllocRealModeCallBack


GetCS function

DPMI Unit

Returns current code segment.

Declaration:

function GetCS: Word;

See also:

GetDS


GetDisableInterruptState function

DPMI Unit

This function will disable the virtual interrupt flag and return the previous state of the virtual interrupt flag.

Declaration:

function GetDisableInterruptState: Boolean;

See also:

GetEnableInterruptState

GetInterruptState


GetDPMIIntVec function

DPMI Unit

This function returns the selector and offest of the current protected mode interrupt handler for the specified interrupt number.

Declaration:

function GetDPMIIntVec(IntNo: Byte; var Sel: Word; var Offs: DWord): Boolean;

Remarks:

Returns True if successful.

See also:

SetDPMIIntVec


GetDPMIVer function

DPMI Unit

Returns the version of DPMI services supported.

Declaration:

function GetDPMIVer: Word;

Remarks:

Returns version of DPMI service if successful. Otherwise returns zero.


GetDS function

DPMI Unit

Returns current code segment.

Declaration:

function GetDS: Word;

See also:

GetCS


GetEnableInterruptState function

DPMI Unit

This function will enable the virtual interrupt flag and return the previous state of the virtual interrupt flag.

Description:

function GetEnableInterruptState: Boolean;

See also:

GetDisableInterruptState

GetInterruptState


GetExceptionHandler function

DPMI Unit

This function returns the pointer to the current protected mode exception handler for the specified exception number.

Declaration:

function GetExceptionHandler(ExpFault: Byte; var Sel: Word; var Offs: DWord): Boolean;

Remarks:

Returns True if successful.

See also:

SetExceptionHandler


GetFreeMemoryInfo function

DPMI Unit

This function is provided so that protected mode applications can determine how much memory is available. Under DPMI implementations that support virtual memory, it is important to consider issues such as the amount of available physical memory.

Declaration:

function GetFreeMemoryInfo (BufferPtr: Pointer): Boolean;

Remarks:

Returns True if successful.


GetInterruptState function

DPMI Unit

This function will disable return state of the virtual interrupt flag.

Declaration:

function GetInterruptState: Boolean;

See also:

GetDisableInterruptState

GetEnableInterruptState


GetRealModeIntVec function

DPMI Unit

This function returns the  value of the current task's real mode interrupt vector for the specified interrupt.

Declaration:

function GetRealModeIntVec(IntNo: Byte; var RSeg,ROfs: Word): Boolean;

Remarks:

Returns segment and offset of real mode interrupt handler.

See also:

SetRealModeIntVec


GetSegmentBaseAddress function

DPMI Unit

This function returns the 32-bit linear base address of the specified segment.

Declaration:

function GetSegmentBaseAddress(Selsctor: Word): DWord;

Remarks:

Returns 32-bit linear base address of segment if successful. Otherwise returns zero.

See also:

GetSelectorAccessRights

SetSelectorAccessRights

SetSelectorBaseAddress


GetSelectorAccessRights function

DPMI Unit

This function returns access rights and type fields of a descriptor.

Declaration:

function GetSelectorAccessRights(Selector: Word): Word;

Remarks:

Returns access rights if successful. Otherwise returns zero.

See also:

GetSegmentBaseAddress

SetSelectorAccessRights

SetSelectorBaseAddress


MapPhysicalToLinear function

DPMI Unit

This function can be used by device drivers to convert a physical address into a linear address. The linear address can then be used to access the device memory.

Declaration:

function MapPhysicalToLinear (PhysAddr, SizeInBytes: DWord): DWord;

Remarks:

Returns pointer to linear address that can be used to access the physical memory. Otherwise returns nil.

See also:

FreePhysicalMap


RealModeInt function

DPMI Unit

This function simulates an interrupt in real mode. It will invoke the CS:IP specified by the real mode interrupt vector and the handler must return by executing an iret.

Declaration:

function RealModeInt(IntNo: Byte; var Regs: TRmRegs): Boolean;

Remarks:

Returns True if successful.

See also:

TRmRegs type

ClearRmRegs

GetRealModeIntVec

SetRealModeIntVec


ResizeDosMemoryBlock function

DPMI Unit

This function is used to grow or shrink a memory block that was allocated through the AllocDosMemoryBlock function.

Declaration:

function ResizeDOSmemoryBlock(Selector: Word; NewSize: DWord): Boolean;

Remarks:

Returns True if successful.

See also:

AllocDosMemoryBlock

FreeDosMemoryBlock


SegmentToDescriptor function

DPMI Unit

This function is used to convert real mode segments into descriptors that are addressable by protected mode programs.

Declaration:

function SegmentToDescriptor(Segment: Word): Word;

Remarks:

Returns selector mapped to real mode segment if successful, or zero.


SelectorInc function

DPMI Unit

Some functions such as allocate LDT descriptors and allocate DOS memory can return more than one descriptor. You must call this function to determine the value that must be added to a selector to access the next descriptor in the array.

Declaration:

function SelectorInc: Word;

Returns:

If successful, returns the value to add to get to next selector. Otherwise returns zero.


SetDPMIIntVec function

DPMI Unit

This function sets the selector and offest of the protected mode interrupt handler for the specified interrupt number.

Declaration:

function SetDPMIIntVec(IntNo: Byte; Sel: Word; Offs: DWord): Boolean;

Remarks:

Returns True if successful.

See also:

GetDPMIIntVec


SetExceptionHandler function

DPMI Unit

This function allows protected mode applications to intercept processor exceptions that are not handled by the DPMI environment. Programs may wish to handle exceptions such as not present segment faults which would otherwise generate a fatal error.

Declaration:

function SetExceptionHandler(ExpFault: Byte; Sel: Word; Offs: DWord): Boolean;

Remarks:

Returns True is successful.

See also:

GetExceptionHandler


SetRealModeIntVec function

DPMI Unit

This function sets the value of the current task's real mode interrupt vector for the specified interrupt.

Declaration:

function SetRealModeIntVec(IntNo: Byte; RSeg, ROfs: Word): Boolean;

Remarks:

Returns True if successful.

See also:

GetRealModeIntVec

RealModeInt


SetSelectorAccessRights function

DPMI Unit

This function allows a protected mode program to modify the access rights and type fields of a descriptor.

Declaration:

function SetSelectorAccessRights(Selector,Rights: Word): Boolean;

Remarks:

Returns True if successful.

See also:

GetSegmentBaseAddress

GetSelectorAccessRights

SetSelectorBaseAddress

SetSelectorLimit


SetSelectorBaseAddress function

DPMI Unit

This function changes the 32-bit linear base address of the specified selector.

Declaration:

function SetSelectorBaseAddress(Selector: Word; Base: DWord): Boolean;

Remarks:

Returns True if successful.

SetSelectorAccessRights

GetSegmentBaseAddress

GetSelectorAccessRights

SetSelectorLimit


SetSelectorLimit function

DPMI Unit

This function sets the limit for the specified segment.

Declaration:

function SetSelectorLimit(Selector: Word; Limit: DWord): Word;

Remarks:

Returns selector if successful. Otherwise returns zero.

See also:

GetSegmentBaseAddress

GetSelectorAccessRights

SetSelectorAccessRights

SetSelectorBaseAddress


The ErrCodes Unit

Contains constants for error codes, given by RunError, and the Error_msg function that deciphers the error code.

Declaration:

Function Error_msg (Err: Word): string;

You should use Error_msg function in your own error handling procedures.

See also:

Run-time Error Codes


The FDebug Unit

This module writes the error code and the call stack to the debug.log file, which will be created automatically in case of a run-time error. The stack is printed as follows:

 RunError #201 (range check error)

 Calls stack:

 SYSTEM.BOUND_ERROR [chk_fun.inp(21) at 0000000A]

 TEST.ASSN [TEST.PAS(61) at 00000015]

 TEST.TEST [TEST.PAS(82) at 0000001D]

To use FDebug, simply list it in the uses clause of the main program. Using the FDebug unit increases the .EXE module size

 A call of a procedure with a NIL address is currently diagnosed as an arithmetic overflow, or (under the PMODE extender) causes a GP Fault or other traps.


The Graph Unit

Introduction

Graph Unit Types, Constants and Variables

Graph Unit Procedures and Functions


Graph Unit Introduction

  The Graph unit for TMT Pascal is as compatible with the Borland Graphics Library as possible. Since BGI is by now an obsolete interface, we added a number of enhancements. They are described in detail below. This graphics library for TMT Pascal allows easy porting of programs written for Borland Pascal (with minimal changes to the source).

Features:

•	Real 32-bit accelerated graphics;

•	Mostly compatible with Borland's GRAPH;

•	Supports the following graphic modes:

−	256-colored VGA/MCGA (13h BIOS) mode;

−	all SVGA 256 color (PaletteColor) modes;

−	all SVGA 32k/64k color (HiColor) modes;

−	all SVGA 16M/16M+A color (TrueColor) modes;

•	VESA VBE 1.2/2.0 features (32-bits PM interface, etc);

•	Banked and LFB (Linear Flat frame Buffer) SVGA modes;

•	Logical pages and hardware scrolling;

•	No 64K limit on sprite size;

•	Does not use BGI drivers;

•	Uses flat memory model for greater performance.

•	Advanced sprite engine with transparent BLT;

•	Virtual graphics mode for DOUBLE and TRIPLE buffering is available.

System Requirements:

•	VGA compatible video card required (VESA VBE 1.2 recomended, VESA VBE 2.0 will be best);

•	CPU Intel 80386 or higher compatible;

•	PMODE, PMODEW or WDOSX compatible DOS extender.

Compatibility with the Graph unit from Borland Pascal.

TMT Graph unit will partly replicate the Graph unit from Borland Pascal. However there are some differences.  Listed below are the names of all procedures and functions from the Graph unit from Borland Pascal 7 and an indication of their status in TMT our Graph unit.

+Arc	+GetMaxX	*PutImage

+Bar	+GetMaxY	+PutPixel

+Bar3D	-GetModeName	*Rectangle

+Circle	-GetModeRange	-RegisterBGIdriver

*ClearDevice	+GetPalette	-RegisterBGIfont

*ClearViewPort	+GetPaletteSize	*RestoreCrtMode

*CloseGraph	+GetPixel	-Sector

-DetectGraph	*GetTextSettings	+SetActivePage

*Drawpoly	+GetViewSettings	+SetAllPalette

+Ellipse	+GetX	*SetAspectRatio

*FillEllipse	+GetY	*SetBkColor

*FillPoly	*GraphDefaults	+SetColor

*FloodFill	+GraphErrorMsg	*SetFillPattern

-GetArcCoords	+GraphResult	*SetFillStyle

*GetAspectRatio	+ImageSize	+SetGraphBufSize

*GetBkColor	-InitGraph	*SetGraphMode

+GetColor	-InstallUserDriver	+SetLineStyle

+GetDefaultPalette	-InstallUserFont	+SetPalette

-GetDriverName	+Line	+SetRGBPalette

+GetFillPattern	+LineRel	+SetTextJustify

-GetFillSettings	+LineTo	*SetTextStyle

*GetGraphMode	+MoveRel	-SetUserCharSize

+GetImage	+MoveTo	*SetViewPort

+GetLineSettings	+OutText	+SetVisualPage

+GetMaxColor	+OutTextXY	*SetWriteMode

-GetMaxMode	-PieSlice	+TextHeight

+TextWidth

Definitions:

+ procedure/function supported and functionally equivalent to Borland;

* procedure/function supported, but somewhat different from Borland;

- procedure/function not supported.

Note that TMT Graph provides many procedures and functions, which are not supported by Borland's Graph unit.


Graph Unit Types, Constants and Variables

DrawBorder

Bar3D constants

BitBlt operators

Clipping constants

Color constants

Fill pattern constants

FillSettingsType

GraphModeType

Graphic result constants

Justification constants

LineSettingsType

Text-Style constants

PaletteType

PointType

RGBType

SVGA mode constants

TextSettingsType

ViewPortType

VbeInfoType

VbeModeInfoType


DrawBorder variable

Graph Unit

You can enable and disable a border drawing for Ellipse, FillCircle, and FillTriangle procedures.

Declaration:

var DrawBorder: Boolean

Remarks:

If DrawBorder = True, border drawing enabled (default).

If DrawBorder = False, border drawing disabled.


Bar3D constants

Graph Unit

These constants are used to specify whether a 3D graph bar has a top. (See Bar3D)

Constant    Value

TopOn	True

TopOff	False


BitBlt operators

Graph Unit

Use these operators for images you place on the screen with PutImage, PutSprite and PutHTextel.

Constant    Value      Meaning

NormalPut	  0	 MOV

CopyPut	  0	 MOV

XORPut	  1	 XOR

OrPut	  2	 OR

AndPut	  3	 AND


Clipping constants

Graph Unit

Constant    Value

ClipOn	True

ClipOff	False


Color constants

Graph Unit

Graph unit defines the following color constants:

clBlack:        DWord =0;

clBlue:         DWord =1;

clGreen:        DWord =2;

clCyan:         DWord =3;

clRed:          DWord =4;

clMagenta:      DWord =5;

clBrown:        DWord =6;

clLightGray:    DWord =7;

clDarkGray:     DWord =8;

clLightBlue:    DWord =9;

clLightGreen:   DWord =10;

clLightCyan:    DWord =11;

clLightRed:     DWord =12;

clLightMagenta: DWord =13;

clYellow:       DWord =14;

clWhite:        DWord =15;

Remarks:

All assigned values above are listed for 256-colored modes only. In HiColor and TrueColor SVGA modes those values will be automatically toned up by the Graph unit to a concrete graphic mode. I.e. those constants actually are constant-variables, which initialize whenever the current color mode changes. You may use color variables to display the same colors in different graphic modes (256-colored, HiColor or TrueColor).


Fill pattern constants

Graph Unit

Constant        Value    Meaning

EmptyFill         0      Uses background color

SolidFill         1      Uses draw color

LineFill          2      --- fill

LtSlashFill       3      /// fill

SlashFill         4      /// thick fill

BkSlashFill       5      \thick fill

LtBkSlashFill     6      \fill

HatchFill         7      Light hatch fill

XHatchFill        8      Heavy cross hatch

InterleaveFill    9      Interleaving line

WideDotFill       10     Widely spaced dot

CloseDotFill      11     Closely spaced dot

UserFill          12     User-defined fill


FillSettingsType

Graph Unit

Declaration:

FillSettingsType = record

  Pattern: DWord;

  Color  : DWord;

end;


GraphModeType

Graph Unit

Declaration:

GraphModeType = record

 VideoMode    : Word;

 HaveLFB      : Boolean;

 BitsPerPixel : Byte;

 XResolution  : Word;

 YResolution  : Word;

end;


Graphic result constants

Graph Unit

Constant                Value

grOK	  0

grInvalidMode	  1

grModeNotSupported	  2

grSetModeError	  3

grLFBSetupError	  4

grError	  5

grVESANotFound	  6

grVESAError	  7


Justification constants

Graph Unit

Use these constants to specify horizontal and vertical justification for SetTextJustify.

Horizontal Constant     Value

LeftText	  0

CenterText	  1

RightText	  2

Vertical Constant       Value

BottomText	  0

CenterText	  1

TopText	  2

Note how each justification constant places the output text relative to the output coordinates:

TopText     TopText  TopText   TopText

LeftText      CenterText       RightText

BottomText    BottomText       BottomText


LineSettingsType

Graph Unit

The record that defines the style, pattern, and thickness of a line.

Declaration:

LineSettingsType = record

    LineStyle : Word;

    Pattern   : Word;

    Thickness : Word;

end;


Text-Style constants

Graph Unit

These constants are used with SetTextStyle and GetTextSettings.

Constant          Value       Meaning

SmallFont	  0	8x8 bit mapped font

MediumFont	  1	8x14 bit mapped font

LargeFont	  2	8x16 bit mapped font


PaletteType

Graph Unit

The record that defines the size and colors of the palette; used by GetPalette, GetDefaultPalette, and SetPalette.

Declaration:

PaletteType = record

  Size    : Byte;

  Colors  : array[0..MaxColors] of DWord;

end;

The size field reports the number of colors in the palette for the current driver in the current mode. Colors contains the actual colors 0..Size - 1.


PointType

Graph Unit

A type defined for your convenience. Both fields are of type Longint rather than Integer.

Declaration:

PointType = record

  X, Y : Longint;

end;


RGBType

Graph Unit

A type used for access to Red, Green and Blue fields of each palette entry.

Declaration:

RGBType = record

  Blue, Green, Red, Aligment: Byte;

end;


SVGA mode constants

Graph Unit

SVGA mode constants used with SetSVGAMode procedure.

Consatnt      Value  Meaning

LFBorBanked     0    LFB mode (if supported) or banked mode

BankedOnly      1    banked mode only

LFBOnly         2    LFB mode only


TextSettingsType

Graph Unit

The record that defines the text attributes used by GetTextSettings.

Declaration:

TextSettingsType = record

  Font           : Pointer;

  FontSize       : DWord;

  FirstChar      : DWord;

  Width          : DWord;

  Height         : DWord;

  Space          : DWord;

  Direction      : DWord;

  Horiz          : DWord;

  Vert           : DWord;

end;


ViewPortType

Graph Unit

A record that reports the status of the current viewport; used by GetViewSettings.

Declaration:

ViewPortType 	= record

   x1, y1, x2, y2 : Longint;

   Clip           : Boolean;

end;

The points (X1, Y1) and (X2, Y2) are the dimensions of the active viewport and are given in absolute screen coordinates. Clip is a Boolean variable that controls whether clipping is active.


VbeInfoType

Graph Unit

A record that stores the VESA VBE information block; used by GetVbeInfo.

Declaration:

VbeInfoType          = record

  VbeSignature       : DWord;

  VbeVersion         : Word;

  OemStringPtr       : DWord;

  Capabilities       : DWord;

  VideoModePtr       : DWord;

  TotalMemory        : Word;

  OEMSoftwareRev     : Word;

  OEMVendorNamePtr   : DWord;

  OEMProductNamePtr  : DWord;

  OEMProductRevPtr   : DWord;

  Reserved           : array [0..221] of Byte;

  OEMData            : array [0..255] of Byte;

end;


VbeModeInfoType

Graph Unit

A record that stores VESA VBE mode information block; used by GetVbeModeInfo.

Declaration:

VbeModeInfoType      = record

  ModeAttributes     : Word;

  WinAAttributes     : Byte;

  WinBAttributes     : Byte;

  WinGranularity     : Word;

  WinSize            : Word;

  WinASegment        : Word;

  WinBSegment        : Word;

  WinFuncPtr         : Pointer;

  BytesPerScanLine   : Word;

  XResolution        : Word;

  YResolution        : Word;

  XCharSize          : Byte;

  YCharSize          : Byte;

  NumberOfPlanes     : Byte;

  BitsPerPixel       : Byte;

  NumberOfBanks      : Byte;

  MemoryModel        : Byte;

  BankSize           : Byte;

  NumberOfImagePages : Byte;

  Reserved           : Byte;

  RedMaskSize        : Byte;

  RedFieldPosition   : Byte;

  GreenMaskSize      : Byte;

  GreenFieldPosition : Byte;

  BlueMaskSize       : Byte;

  BlueFieldPosition  : Byte;

  RsvdMaskSize       : Byte;

  RsvdFieldPosition  : Byte;

  DirectColorModeInfo: Byte;

  PhysBasePtr        : DWord;

  OffScreenMemOffset : DWord;

  OffScreenMemSize   : Word;

  Reserved2          : array [0..205] of Byte;

end;


Graph Unit Procedures and Functions

AnalizeRGBColor

Arc

Bar

Bar3D

Circle

ClearDevice

ClearPage

ClearViewPort

CliRetrace

CliHRetrace

CloseGraph

DetectSVGAMode

DrawEllipse

DrawHLine

DrawPoly

Ellipse

ExpandFill

FillCircle

FillEllipse

FillPoly

FillTriangle

FlipImageOX

FlipImageOY

FlipToMemory

FlipToScreen

FloodFill

GetActivePage

GetAspectRatio

GetBytesPerScanLine

GetColor

GetDefaultPalette

GetFillColor

GetFillPattern

GetFillSettings

GetGraphBufSize

GetGraphMode

GetHTextel

GetImage

GetLfbAddress

GetLineSettings

GetLogicalPage

GetMaxColor

GetMaxPage

GetMaxX

GetMaxY

GetOemProductName

GetOemProductRev

GetOemString

GetOemVendorName

GetPageSize

GetPalette

GetPixel

GetRGBPalette

GetScreenHeight

GetScreenWidth

GetTextSettings

GetTranspSettings

GetVbeCapabilities

GetVbeInfo

GetVbeModeInfo

GetVbeModesList

GetVbeVersion

GetViewSettings

GetVisualPage

GetWriteMode

GetX

GetY

GraphDefaults

GraphErrorMsg

GraphResult

HRetrace

ImageSize

InvertImage

IsLfbUsed

Line

LineRel

LineTo

MoveRel

MoveTo

OutCharXY

OutText

OutTextXY

PutHTextel

PutImage

PutPixel

PutSprite

Rectangle

RestoreCrtMode

Retrace

RGBColor

SetActivePage

SetAllPalette

SetAspectRatio

SetBkColor

SetColor

SetCustomFont

SetFillColor

SetFillPattern

SetFillStyle

SetGraphBufSize

SetGraphMode

SetLineStyle

SetLogicalPage

SetNormalMode

SetPalette

SetRGBPalette

SetScreenStart

SetSVGAMode

SetTextJustify

SetTextStyle

SetSplineLineSteps

SetTranspMode

SetViewPort

SetVirtualMode

SetVisualPage

SetWriteMode

Spline

Stretch

TextHeight

TextWidth

TotalVbeMemory

TotalVbeModes

Triangle


AnalizeRGBColor procedure

Graph Unit

Returns RGB fields of given color.

Declaration:

procedure AnalizeRGB(Color: DWord; var R,G,B: Byte);

Remarks:

This function works in HiColor and TrueColor SVGA modes only. RGB field values, returned by AnalizeRGB depended on the current video mode (32K, 64K or 16M colors).


Arc procedure

Graph Unit

Draws a circular arc.

Declaration:

procedure Arc(X, Y; Integer; StAngle, EndAngle, Radius; Word);

Remarks:

The arc begins at StAngle (start angle) and ends at EndAngle, with radius Radius, and with (X,Y) as the center point.


Bar procedure

Graph Unit

Draws a bar with the current fill color.

Declaration:

procedure Bar(X1, Y1, X2, Y2: Longint);

Remarks:

Bar draws a filled-in rectangle (used in bar charts, for example). It uses style and color defined by SetFillColor, SetFillPattern or SetFillStyle. To draw an outlined bar, call Bar3D with a zero depth.


Bar3D procedure

Graph Unit

Draws a 3-D bar using the current fill color.

Declaration:

procedure Bar3D(X1, Y1, X2, Y2: DWord; Depth: Word; Top: Boolean);

Remarks:

Bar3D draws a filled-in, three-dimensional bar with the pattern and color defined by SetFillColor, SetFillPattern or SetFillStyle. The 3-D outline of the bar is drawn in the current line style and color as set by SetLineStyle and SetColor. Depth is the length in pixels of the 3-D outline. If Top is TopOn, a 3-D top is put on the bar; if Top is TopOff, no top is put on the bar (making it possible to stack several bars on top of one another).

A typical depth could be calculated by taking 25% of the width of the bar:

Bar3D(X1, Y1, X2, Y2, (X2 - X1 + 1) div 4, TopOn);


Circle procedure

Graph Unit

Draws a circle in the current color set by SetColor, using (X,Y) as the center point.

Declaration:

procedure Circle(X,Y: Longint; Radius: DWord);

procedure Circle(X,Y: Longint; Radius, Color: DWord);

Remarks:

Draws a circle in the current color set by SetColor. Each graphics mode has an aspect ratio used by Circle.


ClearDevice procedure

Graph Unit

Clears the currently selected output device and homes the current pointer.

Declaration:

procedure ClearDevice;

Remarks:

ClearDevice moves the current pointer to (0, 0), and clears all accessible video memory with zero value.


ClearPage procedure

Graph Unit

Clears the current active page using the background color set by SetBkColor and moves the current pointer to (0, 0).

Declaration:

procedure ClearPage;

Remarks:

Active logical page sets by SetLogicalPage may be larger than the physical screen.


ClearViewPort procedure

Graph Unit

Clears the current view port using the background color set by SetBkColor and moves the current pointer to (0, 0).

Declaration:

procedure ClearViewPort;

Remarks:

ClearViewPort sets the fill color to the background color and moves the current pointer to (0, 0).


CliRetrace procedure

Graph Unit

Switches off interrupts, waits for vertical retrace and restore interrupts.

Declaration:

procedure CliRetrace;


CliHRetrace procedure

Graph Unit

Switches off interrupts, waits for horizontal retrace and restore interrupts.

Declaration:

procedure CliHRetrace;


CloseGraph procedure

Graph Unit

Shuts down the graphics system.

Declaration:

procedure CloseGraph;

Remarks:

CloseGraph restores the original screen mode before graphics was initialized the first time and frees the memory allocated for the graphics buffer.


DetectSVGAMode procedure

Graph Unit

Returns a valid VESA VBE mode number for the requested video mode. If the requested video mode is not supported, returns a zero value.

Declaration:

function DetectSVGAMode(XRes, YRes, BPP, VMode: Word): Word;

Remarks:

This function may be used with the SetGraphMode procedure. The following example tries to set the SVGA mode 640x480 with maximum color depth:

uses Crt, Graph;

function SetSVGA640x480: String;

const Bps: array [0..4] of Word = (32, 24, 16, 15, 8);

var   Mode,i: Word;

begin

  for I := 0 to 4 do begin

    Mode:=DetectSVGAMode(640, 480, bps[i], LfbOrBanked);

    if Mode > 0 then begin

      SetGraphMode(Mode);

      if GraphResult = grOk then begin

        Str(bps[i], Result);

        exit;

      end;

    end;

  end;

  RestoreCrtMode;

  Result := '';

end;

// main program

var S: String;

begin

 S := SetSVGA640x480;

 if S <> '' then begin

  SetTextJustify(CenterText, CenterText);

  OutTextXY(320, 240, 'This is SVGA mode 640x480 ' + S + ' bps');

  OutTextXY(320, 260, 'Press any key...');

  ReadKey;

  RestoreCrtMode;

 end else

  Writeln('SVGA mode 640x480 not supported.');

end.


DrawEllipse procedure

Graph Unit

Draws an ellipse

Declaration:

procedure DrawEllipse(X, Y, A, B: Longint)

Remarks:

(X,Y) is the center point; A and B are the horizontal and vertical axes.


DrawHLine procedure

Graph Unit

Draws a horizontal line using the current fill color.

Declaration:

procedure DrawHLine(X1,X2,Y: Longint);


DrawPoly procedure

Graph Unit

Draws the outline of a polygon using the current line style and color.

Declaration:

procedure DrawPoly(NumVert: DWord; var Vert);

Remarks:

Numvert specifies the number of coordinate pairs in Vert. A coordinate pair consists of two Longint values, an X and a Y value.


Ellipse procedure

Graph Unit

Draws a portion of an ellipse.

Declaration:

procedure Ellipse(X, Y: Longint; StAngle, EndAngle, XRadius, YRadius: DWord);

Remarks:

Draws an arc from StAngle (start angle) to EndAngle, with radii Xradius and YRadius, and (X,Y) as the center point.


ExpandFill procedure

Graph Unit

Draws a portion of an ellipse.

Fills a bounded region with the current color.

Declaration:

procedure ExpandFill(X, Y: Integer);

Remarks:

Fills an enclosed area on bitmap devices. (X, Y) is a seed within the enclosed area to be filled. The current fill color, as set by SetFillColor, is used to flood the area bounded by any different color. If the seed point is within an enclosed area, then the inside will be filled. If the seed is outside the enclosed area, then the outside will be filled.


FillCircle procedure

Graph Unit

Draws a filled circle in the current color set by SetColor, using (X,Y) as the center point.

Declaration:

procedure FillCircle(X,Y: Longint; Radius: DWord);

Remarks:

Draws a circle in the current color set by SetColor and fill it using the current fill style and color defined by SetFillColor, SetFillPattern or SetFillStyle. Each graphics mode has an aspect ratio used by Circle.


FillEllipse procedure

Graph Unit

Draws a filled ellipse

Declaration:

procedure FillEllipse(X, Y, A, B: Longint)

Remarks:

Draws an ellipse in the current color set by SetColor and fill it using the current fill style and color defined by SetFillColor, SetFillPattern or SetFillStyle. (X,Y) is the center point; A and B are the horizontal and vertical axes.


FillPoly procedure

Graph Unit

Fills a polygon, using the scan converter

Declaration:

procedure FillPoly(NumVert: DWord; var Vert);

Remarks:

Vert is an untyped parameter that contains the coordinates of each vertex in the polygon. NumVert specifies the number of coordinate pairs in Vert. A coordinate pair consists of two Longint values, an X and a Y value. FillPoly calculates all the horizontal intersections, and then fills it using the current fill style and color defined by SetFillColor, SetFillPattern or SetFillStyle. This function is different from Borland's GRAPH unit. Polygons must have angles less than 180 degrees. That is, they must be convex.

	1) Valid polygon		2) Invalid polygon
If you want to draw polygon (2), you must split it up into two valid polygons:

		+		=


FillTriangle procedure

Graph Unit

Draws a filled triangle.

Declaration:

procedure FillTriangle(X1, Y1, X2, Y2, X3, Y3: Longint);

Remarks:

Draws a triangle in the current color set by SetColor and fill it using the current fill style and color defined by SetFillColor, SetFillPattern or SetFillStyle.


FlipImageOX procedure

Graph Unit

Flips an image (BitMap) left to right.

Declaration:

procedure FlipImageOX(var BitMap);

Remarks:

See FlipImageOY for example.


FlipImageOY procedure

Graph Unit

Flips an image (BitMap) top to bottom.

Declaration:

procedure FlipImageOY(var BitMap);

Example:

uses Graph, CRT;

var P: Pointer;

    i, j, dx, dy: DWord;

begin

 (* Set SVGA mode 640x480x256. You can set ANY supported mode *)

 SetSVGAMode(640, 480, 8, LfbOrBanked);

 if GraphResult <> grOk then begin

  ClrScr;

  Writeln(GraphErrorMsg(GraphResult));

  exit;

 end;

 dx := (GetMaxX + 1) div 2;

 dy := (GetMaxY + 1) div 2;

 for i := 0 to dx do

  for j := 0 to dy do

   PutPixel(i, j, i * j div dx);

 SetTextJustify(CenterText, BottomText);

 OutTextXY(dx, dy + dy div 2, 'Press any key...');

 ReadKey;

 GetMem(P, ImageSize(0, 0, dx - 1, dy - 1));

 GetImage(0, 0, dx - 1 , dy - 1, P^);

 FlipImageOX(P^);

 PutImage(dx, 0, P^);

 FlipImageOY(P^);

 PutImage(dx, dy, P^);

 FlipImageOX(P^);

 PutImage(0, dy, P^);

 ReadKey;

 FreeMem(P, ImageSize(0, 0, dx - 1, dy - 1));

 RestoreCrtMode;

end.


FlipToMemory procedure

Graph Unit

Copies contents of graphic page number 0 to memory buffer pointed by Addr.

Declaration:

procedure FlipToMemory(Addr: Pointer)

Remarks:

Use this procedure to flip the contents of the graphic page into the virtual page.

See also:

FlipToScreen, SetVirtualMode, SetNormalMode


FlipToScreen procedure

Graph Unit

Copies contents of memory buffer pointed by Addr to graphic page number 0.

Declaration:

procedure FlipToScreen(Addr: Pointer)

Remarks:

Use this procedure to flip the contents of the virtual page into the graphic page.

See also:

FlipToMemory, SetVirtualMode, SetNormalMode


FloodFill procedure

Graph Unit

Fills a bounded region with the current color.

Declaration:

procedure FloodFill(X, Y: Integer; Border: Word);

Remarks:

Fills an enclosed area on bitmap devices. (X, Y) is a seed within the enclosed area to be filled. The current fill color, as set by SetFillColor, is used to flood the area bounded by Border color. If the seed point is within an enclosed area, then the inside will be filled. If the seed is outside the enclosed area, then the exterior will be filled.


GetActivePage function

Graph Unit

Returns the current active page number.

Declaration:

function GetActivePage: DWord;


GetAspectRatio procedure

Graph Unit

Returns current aspect ratio factor.

Declaration:

procedure GetAspectRatio(var AspectRatio: Real);

Remarks:

See the SetAspectRatiomore info.


GetBytesPerScanLine function

Graph Unit

Returns scan line size in bytes.

Declaration:

function GetBytesPerScanLine: DWord;


GetColor function

Graph Unit

Returns the current drawing color.

Declaration:

function GetColor: DWord;


GetDefaultPalette procedure

Graph Unit

Returns the palette definition structure.

Declaration:

procedure GetDefaultPalette(var Palette: PaletteType);

This structure contains the palette as the new graphic mode initialized.

Remarks:

GetDefaultPalette returns a record of PaletteType, which contains the palette.


GetFillColor function

Graph Unit

Returns the current fill color as set by SetFillColor.

Declaration:

function GetColor: DWord;


GetFillPattern procedure

Graph Unit

Returns the currently selected fill pattern and color as set by SetFillStyle or SetFillPattern.

Declaration:

procedure GetFillPattern(var FillPattern: FillPatternType);

Remarks:

If no user call has been made to SetFillPattern, GetFillPattern returns an array filled with $FF.


GetFillSettings procedure

Graph Unit

Gets the current fill pattern and color, as set by SetFillStyle, SetFillPattern or SetFillColor.

Declaration:

procedure GetFillSettings(var FillInfo: FillSettingsType);

Remarks:

The Pattern field reports the current fill pattern selected. The colors field reports the current fill color selected. Both the fill pattern and color can be changed by calling the SetFillStyle, SetFillPattern or SetFillColor procedure.

If Pattern is equal to UserFill, use GetFillPattern to get the user-defined fill pattern that is selected.

See also:

FillSettingsType


GetGraphBufSize function

Graph Unit

Returns the size of internal graphic buffer;

Declaration:

function GetGraphBufSize: DWord;

Remarks:

See the SetGraphBufSize procedure.


GetGraphMode function

Graph Unit

Returns VESA-compatible mode number of current graphic mode.

Declaration:

function GetGraphMode: Word;

Remarks:

The mode number returned by GetGrapMode may be used with SetGraphMode.


GetHTextel procedure

Graph Unit

Gets horizontal set of pixels (horizontal textel) from the screen and puts it into memory.

Declaration:

procedure GetHtextel(X1, X2, Y: Longint; var Textel);


GetImage procedure

Graph Unit

Saves a bit image of the specified region into a buffer.

Declaration:

procedure GetImage(X1, Y1, X2, Y2: Integer; var BitMap);

Remarks:

X1, Y1, X2, and Y2 are the coordinates of diagonally opposite points of the rectangular region on the screen. BitMap is an untyped parameter that must be at least 4 greater than the amount of area defined by the region. The first two words of BitMap store the width and height of the region.

The remaining part of BitMap is used to save the bit image itself. Use the ImageSize function to determine the size requirements of BitMap.


GetLfbAddress function

Graph Unit

Returns the physical address of linear flat frame buffer.

Declaration:

function GetLfbAddress: DWord;

Remarks:

If LFB is not supported, the function returns zero.


GetLineSettings procedure

Graph Unit

Returns the current line style, line pattern, and line thickness, as set by SetLineStyle.

Declaration:

procedure GetLineSettings(var LineInfo: LineSettingsType);


GetLogicalPage procedure

Graph Unit

Returns the current logical page size.

Declaration:

procedure GetLogicalPage(var SX, SY: Word);

Remarks:

See the SetLogicalPage procedure for more info.


GetMaxColor function

Graph Unit

Returns the highest color that can be passed to the SetColor procedure.

Declaration:

function GetMaxColor: DWord;

Remarks:

For example, on a 256 colored VGA/SVGA mode, GetMaxColor always returns 255, which means that any call to SetColor with a value from 0..255 is valid. On an SVGA in high-color mode, GetMaxColor returns a value of 32767 or 65535, etc.


GetMaxPage function

Graph Unit

Returns the number of the last accessible graphic page.

Declaration:

function GetMaxPage: DWord;


GetMaxX function

Graph Unit

Gets current X resolution.

Declaration:

function GetMaxX: DWord;

Remarks:

Returns the rightmost column (X resolution) of the logical visual page in the current graphics mode.


GetMaxY function

Graph Unit

Gets current Y resolution.

Declaration:

function GetMaxX: DWord;

Remarks:

Returns the bottommost row (Y resolution) of the logical visual page in the current graphics mode.


GetOemProductName function

Graph Unit

Returns the string containing the name of the display controller board.

Declaration:

function GetOemProductName: String;

Remarks:

If VESA VBE 2.0+ is not supported, this function will return an empty string.


GetOemProductRev function

Graph Unit

Returns the string revision or manufacturing level of the display controller board product.

Declaration:

function GetOemProductRev: String;

Remarks:

If VESA VBE 2.0+ is not supported, this function will return an empty string.


GetOemString function

Graph Unit

Returns the OEM-defined string.

Declaration:

function GetOemString: String;

Remarks:

This string may be used to identify the graphics controller chip or OEM product family for hardware specific display drivers. If VESA VBE 1.2+ is not supported, this function will return an empty string.


GetOemVendorName function

Graph Unit

Returns the string containing the name of the vendor which produced the display controller board product.

Declaration:

function GetOemVendorName: String;

Remarks:

If VESA VBE 2.0+ is not supported, this function will return an empty string.


GetPageSize function

Graph Unit

Returns size (in bytes) of the logical video page in the current graphic mode.

Declaration:

function GetPageSize: DWord;

Remarks:

Size of graphic page depends on the graphic mode and size of logical pages, installed by the SetLogicalPage.


GetPalette procedure

Graph Unit

Returns the current palette and its size.

Declaration:

procedure GetPalette(var Palette: PaletteType);

Remarks:

Returns the current palette and its size in a variable of PaletteType.


GetPixel function

Graph Unit

Gets the pixel value (color) at (X,Y).

Declaration:

function GetPixel(X, Y: Longint): DWord;


GetRGBPalette procedure

Graph Unit

Returns palette entries for the VGA, MCGA and 256-colored SVGA modes.

Declaration:

procedure GetRGBPalette(ColorNum: Byte; var RedValue, GreenValue, BlueValue: Byte);

Remarks:

ColorNum defines the palette entry to be returned. RedValue, GreenValue, and BlueValue return the component colors of the palette entry.


GetScreenHeight function

Graph Unit

Returns the height in pixels of the physical screen.

Declaration:

function GetScreenHeight: DWord;


GetScreenWidth function

Graph Unit

Returns the width in pixels of the physical screen.

Declaration:

function GetScreenWidth: DWord;


GetTextSettings procedure

Graph Unit

Gets settings for text output in graphics mode.

Declaration:

procedure GetTextSettings(var TextInfo: TextSettingsType);

Remarks:

Returns the current text font, direction, size, and justification as set by SetTextStyle or SetCustomFont and SetTextJustify.


GetTranspSettings procedure

Graph Unit

Returns current transparent mode settings.

Declaration:

procedure GetTranspSettings(var Mode: Boolean; var Color: DWord);

Remarks:

See the SetTranspMode for more info.


GetVbeCapabilities function

Graph Unit

Returns VESA VBE capabilities field.

Declaration:

function GetVbeCapabilities: DWord;


GetVbeInfo procedure

Graph Unit

Returns VESA VBE info.

Declaration:

procedure GetVbeInfo(var VbeInfo: VbeInfoType);

Remarks:

VbeInfo must be of VbeInfoType. You don't need to allocate a real mode memory block for the VBE Information Table. TMT Graph translates it from real mode memory into vi so you can directly access it from normal Pascal code.


GetVbeModeInfo procedure

Graph Unit

Returns the video mode information for the specified VBE internal video mode number.

Declaration:

procedure GetVbeModeInfo(ModeNo: Word; var VbeModeInfo: VbeModeInfoType);

Remarks:

VbeModeInfo must be of VbeModeInfoType. You don't need to allocate real mode memory block for VBE Mode Information Table. TMT Graph translates it from real mode memory into VbeModeInfo so you can directly access it from normal Pascal code.


GetVbeModesList procedure

Graph Unit

Returns list of supported VESA VBE modes.

Declaration:

procedure GetVbeModesList(var ModesList: array of GraphModeType);

Remarks:

Check ModesList structure to get information about all supported modes.

See also: GraphModeType


GetVbeVersion function

Graph Unit

Returns the version of VESA BIOS Implementation.

Declaration:

function GetVbeVersion: Word

Remarks:

The Vbe version is a BCD value which specifies what level of the VBE standard is implemented in the software. The higher byte specifies the major version number. The lower byte specifies the minor version number. Note: The BCD value for VBE 2.0 is 0200h and the BCD value for VBE 1.2 is 0102h. In the past we have had some applications misinterpreting these BCD values. For example, BCD 0102h was interpreted as 1.02, which is incorrect.


GetViewSettings procedure

Graph Unit

Gets the current viewport and clipping parameters.

Declaration:

procedure GetViewSettings(var ViewPort: ViewPortType);

Remarks:

GetViewSettings returns a variable of ViewPortType.


GetVisualPage function

Graph Unit

Gets the current visual page number.

Declaration:

function GetVisualPage: DWord;


GetWriteMode function

Graph Unit

Returns the current write mode.

Declaration:

function GetWriteMode: DWord;


GetX function

Graph Unit

Returns the X coordinate of the current pointer (CP).

Declaration:

function GetX: Longint;


GetY function

Graph Unit

Returns the Y coordinate of the current pointer (CP).

Declaration:

function GetY: Longint;


GraphResult function

Graph Unit

Returns an error code for the last graphics operation.

Declaration:

function GraphResult: Integer;

See also: Graphic result constants


GraphDefaults procedure

Graph Unit

Homes the current pointer (CP) and resets the graphics system to specified default values.

Declaration:

procedure GraphDefaults;

Remarks:

Homes the current pointer (CP) and resets the graphics system to the default values for:

  viewport

  palette

  draw and background colors

  line style and line pattern

  fill color

  active font, text style, text justification, and user Char size


GraphErrorMsg function

Graph Unit

Returns error message string for the specified ErrorCode.

Declaration:

function GraphErrorMsg(ErrorCode: Integer): string;

See also:

Graph Error Constants


HRetrace procedure

Graph Unit

Waits for horizontal retrace.

Declaration:

procedure HRetrace;


ImageSize function

Graph Unit

Returns the number of bytes required to store a rectangular region of the screen.

Declaration:

function ImageSize(X1, Y1, X2, Y2: Longint): DWord;

Remarks:

X1, Y1, X2, and Y2 are the coordinates of diagonally opposite vertices of a rectangular region on the screen. ImageSize determines the number of bytes necessary for GetImage to save the specified region of the screen. The image size includes space for two words. The first stores the width of the region and the second stores the height.


InvertImage procedure

Graph Unit

Inverts an image.

Declaration:

procedure InvertImage(var BitMap);

Remarks:

This procedure performs the logical NOT operation on each byte of the BitMap Image.


IsLfbUsed function

Graph Unit

Returns True if Linear Flat framebuffer is used by the current graphic

mode.

Declaration:

function IsLFBUsed: Boolean;


Line procedure

Graph Unit

Draws a line from the point (X1, Y1) to (X2, Y2).

Declaration:

procedure Line(X1, Y1, X2, Y2: Longint);

procedure Line(X1, Y1, X2, Y2: Longint; Color: DWORD);

Remarks:

Draws a line in the style defined by SetLineStyle and uses the color set by SetColor. Use SetWriteMode to determine whether the line is copied or XOR'd to the screen.

Note that

 MoveTo(100, 100);

 LineTo(200, 200);

is equivalent to

 Line(100, 100, 200, 200);

 MoveTo(200, 200);

Use LineTo when the current pointer (CP) is at one endpoint of the line. If you want the CP updated automatically when the line is drawn, use LineRel  to draw a line relative the current pointer (CP). Line doesn't update the CP.


LineRel procedure

Graph Unit

Draws a line relative to the current pointer (CP) and moves the CP to (X1, X1).

Declaration:

procedure LineRel(Dx, Dy: LongInt);

Remarks:

Draws the line from the CP (X0, Y0) to a point (X1, Y1), where

 x1 = x0 + Dx

 y1 = y0 + Dy


LineTo procedure

Graph Unit

Draws a line from the current pointer to (X,Y).

Declaration:

procedure LineTo(X, Y: Longint);

Remarks:

Draws a line in the style SetLineStyle and uses the color set by SetColor. Use SetWriteMode to determine whether the line is copied or XOR'd to the screen.

Note that

 MoveTo(100, 100);

 LineTo(200, 200);

is equivalent to

 Line(100, 100, 200, 200);

The first method is slower and uses more code. Use LineTo only when the current pointer is at one endpoint of the line. Use LineRel to draw a line a relative distance from the CP. The second method doesn't change the value of the CP.

LineTo moves the current pointer to (X, Y).


MoveRel procedure

Graph Unit

Displaces the current pointer (CP) from its current position.

Declaration:

procedure MoveRel(Dx, Dy: Longint);

Remarks:

If the CP is at (X1,Y1), MoveRel moves it to ((X1 + Dx),(Y1 + Dy)).


MoveTo procedure

Graph Unit

Moves the current pointer (CP) to (X,Y).

Declaration:

procedure MoveTo(X, Y: Longint);

Remarks:

The CP is similar to a text mode cursor except that the CP is not visible. The following routines move the CP:

 ClearDevice

 ClearViewPort

 GraphDefaults

 SetGraphMode

 SetSVGAMode

 LineRel

 LineTo

 MoveRel

 MoveTo

 OutText

 SetViewPort


OutCharXY procedure

Graph Unit

Sends a char to the output device.

Declaration:

procedure OutCharXY(X, Y: Longint; C: Char; Color: DWord);

Remarks:

Displays char C at (X, Y) using given Color.

OutCharXY has no affects on the CP.


OutText procedure

Graph Unit

Sends a string to the output device at the current pointer.

Declaration:

procedure OutText(TextString: string);

Remarks:

Displays TextString at the CP using the current justification settings.

TextString is truncated at the viewport border if it is too long.

OutText uses the font set by SetTextStyle. To maintain code compatibility when using several fonts, use the TextWidth and TextHeight calls to determine the dimensions of the string.

OutText uses the output options set by SetTextJustify (justify and center).

The CP is updated by OutText only if the direction is horizontal with left justification. Text output direction is set by SetTextStyle (horizontal or vertical); text justification is set by SetTextJustify (CP at the left of the string, centered around CP, or CP at the right of the string--written above CP, below CP, or centered around CP).


OutTextXY procedure

Graph Unit

Sends a string to the output device.

Declaration:

procedure OutTextXY(X, Y: Longint; TextString: string);

Remarks:

Displays TextString at (X, Y). TextString is truncated at the viewport border if it is too long. Use OutText to output text at the current pointer; use OutTextXY to output text elsewhere on the screen. OutTextXY uses the font set by SetTextStyle. To maintain code compatibility when using several fonts, use the TextWidth and TextHeight calls to determine the dimensions of the string. OutTextXY uses the output options set by SetTextJustify (justify and center).


PutHTextel procedure

Graph Unit

Puts horizontal set of pixels (horizontal textel) onto the screen.

Declaration:

procedure PutHtextel(X1, X2, Y: Longint; var Textel);


PutImage procedure

Graph Unit

Puts a bit image onto the screen.

Declaration:

procedure PutImage(X, Y: Longint; var BitMap);

Remarks:

(X, Y) is the upper left corner of a rectangular region on the screen. BitMap is an untyped parameter that contains the height and width of the region, and the bit image that will be put onto the screen.


PutPixel procedure

Graph Unit

Plots a pixel at (X,Y).

Declaration:

procedure PutPixel(X, Y: Longint; Pixel: DWord);

procedure PutPixel(X, Y: Longint);

Remarks:

Plots a point in the color defined by Pixel at (X, Y).


PutSprite procedure

Graph Unit

Puts a bit sprite onto the screen.

Declaration:

procedure PutSprite(X1, Y1, X2, Y2: Longint; var Sprite);


Rectangle procedure

Graph Unit

Draws a rectangle, using the current line style and color.

Declaration:

procedure Rectangle(X1, Y1, X2, Y2: Longint);

procedure Rectangle(X1, Y1, X2, Y2: Longint; Color: DWORD);

Remarks:

(X1, Y1) defines the upper left corner of the rectangle, and (X2, Y2) defines the lower right corner. The rectangle can cross the screen borders.

Draws the rectangle in the current line style and color, as set by SetLineStyle and SetColor. Use SetWriteMode to determine whether the rectangle is copied or XOR'd to the screen.


RestoreCrtMode procedure

Graph Unit

Restores the original screen mode before graphics was initialized the first time.

Declaration:

procedure RestoreCrtMode;

Remarks:

Restores the original video mode detected by first SetGraphMode or SetSVGAMode execution. Can be used in conjunction with SetGraphMode and SetSVGAMode to switch back and forth between text and graphics modes.


Retrace procedure

Graph Unit

Waits for vertical retrace.

Declaration:

procedure Retrace;


RGBColor procedure

Graph Unit

Packs a set of RGB values into a color value for passing to the primitive drawing routines that is appropriate for the current video mode.

Declaration:

function RGBColor(R, G, B: Byte): DWord;

Remarks:

This routine is intended to work with RGB video modes such as the 15, 16, 24 and 32 bits per pixel modes.

Use this routine to convert all color values to ensure that they work correctly on the different types of direct color video modes available.


SetActivePage procedure

Graph Unit

Set the active page for graphics output.

Declaration:

procedure SetActivePage(Page: DWord);

Remarks:

Makes Page the active graphics page, directing all subsequent graphics

output to Page.

Multiple pages are supported only by the SVGA graphics cards. With multiple graphics pages, a program can direct graphics output to an offscreen page, then quickly display the offscreen image by changing the visual page with the SetVisualPage procedure. This technique is especially useful for animation.


SetAllPalette procedure

Graph Unit

Changes all palette colors as specified.

Declaration:

procedure SetAllPalette (var Palette);


SetAspectRatio procedure

Graph Unit

Changes the default aspect-ratio correction factor.

Declaration:

procedure SetAspectRatio(AspectRatio: Real);

Remarks:

SetAspectRatio is used to change the default aspect ratio of the current graphics mode. The aspect ratio is used to draw circles. If circles appear elliptical, the monitor is not alligned properly. This can be corrected in hardware by realigning the monitor, or it can be corrected in software by changing the aspect ratio using SetAspectRatio. To read the current aspect ratio from the system, use GetAspectRatio.


SetBkColor procedure

Graph Unit

Sets the current background color, using the palette.

Declaration:

procedure SetBkColor(ColorNum: Word);

Remarks:

Background color must be in range range [0..GetMaxColor], depending on the current graphics driver and the current graphics mode. The background color is used by the ClearViewPort and ClearPage procedures. SetBkColor does not change the first color in the active palette! To change it, use the GetRGBPalette and SetRGBPalette procedures.


SetColor procedure

Graph Unit

Sets the current drawing color, using the palette.

Declaration:

procedure SetColor(Color: DWord);

Remarks:

Drawing colors must be in range [0..GetMaxColor, depending on the current graphics driver and the current graphics mode.


SetCustomFont procedure

Graph Unit

Sets user-defined bit-fonts.

Declaration:

procedure SetCustomFont(AddrPtr: Pointer; Width, Height, Start, Space: DWord);

Remarks:

AddrPtr points to the fonts data location in memory.  The Width parameter is the horizontal size of char (in pixels) divided by 8. Height is the vertical size of the char (in pixels). The Start parameter is an offset of first symbol in the char's table.


SetFillColor procedure

Graph Unit

Selects a user-defined fill color.

Declaration:

procedure SetFillColor(Color: DWord);

Remarks:

Sets the color for all filling done by FillPoly, Bar, Bar3D, FillCircle, FillEllipse, FloodFill and ExpandFill. This procedure cancels the settings made by SetFillStyle and enables a solid fill mode.


SetFillPattern procedure

Graph Unit

Selects a user-defined fill pattern.

Declaration:

procedure SetFillPattern(Pattern: FillPatternType; Color: DWord);

Remarks:

Sets the fill pattern for all filling done by FillPoly, Bar, Bar3D, FillCircle, FillEllipse and FillTriangle procedures. The Graph unit does not support pattern fill for FloodFill and ExpandFill procedures.

FillPatternType is predefined as follows:

type

  FillPatternType = array[1..8] of byte;

See also

SetFillColor


SetFillStyle procedure

Graph Unit

Sets the fill pattern and color.

Declaration:

procedure SetFillStyle(Pattern: DWord; Color: DWord);

Remarks:

Sets the pattern and color for all filling done by FillPoly, Bar, Bar3D, FillCircle, FillEllipse and FillTriangle procedures. The Graph unit does not support pattern fill for FloodFill and ExpandFill procedures. If invalid input is passed to SetFillStyle, GraphResult returns a value of grError, and the current fill settings will be unchanged. If Pattern equals UserFill, the user-defined pattern (set by a call to SetFillPattern) becomes the active pattern.

See also

SetFillColor

SetFillPattern


SetGraphBufSize procedure

Graph Unit

Changes the default graphics buffer size used for ellipse drawing.

Declaration:

procedure SetGraphBufSize(BufSize: DWord);

Remarks:

The internal buffer size is set to BufSize, and a buffer is allocated on call is made to SetGraphMode or SetSVGAMode. CloseGraph frees the allocated buffer. Use GetGraphBufSize to get the size in bytes of the internal graphic buffer.


SetGraphMode procedure

Graph Unit

Sets the system to graphics mode and clears the screen.

Declaration:

procedure SetGraphMode(Mode: Word);

Remarks:

Mode must be a valid mode for the current video adapter. This procedure supports all VESA VBE graphic modes (100h - FFFh), which are supported by video adapter.

Example:

 SetGraphMode($101) // set SVGA 256-colored mode 640x480;

 SetGraphMode($114) // set SVGA 64K-colored mode 800x600;

 SetGraphMode($12A) // set SVGA 16M+A-colored mode 1024x768;

Keep in mind what your video card may not support all these modes. See GetVbeModesList and TotalVbeModes.


SetLineStyle procedure

Graph Unit

Sets the current line width and style.

Declaration:

procedure SetLineStyle(LineStyle: Word; Pattern: Word; Thickness: Word);

Remarks:

Affects all lines drawn by Line, LineTo, LineRel, Rectangle, DrawPoly, and so on. Lines can be drawn solid, dotted, centerline, or dashed. If invalid input is passed to SetLineStyle, GraphResult returns a value of grError, and the current line settings will be unchanged. See LineSettingsType for a list of constants used to determine line styles.

LineStyle is a value from SolidLn to UserBitLn(0..4), Pattern is ignored unless LineStyle equals UserBitLn, and Thickness is NormWidth or ThickWidth. When LineStyle equals UserBitLn, the line is output using the 16-bit pattern defined by the Pattern parameter. For example, if Pattern = $AAAA, then the 16-bit pattern looks like this:

1010101010101010	{ NormWidth }

1010101010101010	{ ThickWidth }

1010101010101010

1010101010101010


SetLogicalPage procedure

Graph Unit

Sets the logical page size. The SX and SY valus are the new logical size.

Declaraton:

procedure SetLogicalPage(SX, SY: Word);

Remarks:

Many SVGA adapters support logical pages. A logical page can exceed the size of the physical screen. For instance, it is possible to install a logical page 1280 x 480 with a screen of physical resolution 640x480. In this case only half the logical page will be seen on the screen. Logical pages are used for hardware scrolling. The maximum size logical pages depend on the SVGA adapter and the size of the video memory. Use the function GetLogicalPage to get the current logical page size. Remember that the number of available graphic pages depends on the logical page size. Thus SetLogicalPage influences the number of available graphic pages and resets viewport to the whole logical page size. Keep in mind, that SX and SY can't be less than the physical screen size. Here is an example of use of the logical page:

// This example sets a logical page 1280x600 and performs

// hardware scrolling

// VESA-compatible SVGA card with 1Mb required

//

uses Graph,Crt;

var ErrorCode,i: Longint;

    SX, SY: Word;

begin

 // setup SVGA mode 640x480x256

 SetSVGAMode(640, 480, 8, LfbOrBanked);

 ClearDevice;

 if GraphResult <> 0 then begin

  ErrorCode:=GraphResult;

  CloseGraph;

  Writeln(GraphErrorMsg(ErrorCode));

 end;

 // setup logical page 1280x600

 SetLogicalPage(1280, 600);

 // check logical page size

 GetLogicalPage(SX, SY);

if (SX = 640) and (SY = 480) then begin

  CloseGraph;

  Writeln(' Logical pages not supported...');

 end;

 // draw on logical page

 SetLineStyle(SolidLn, 0, ThickWidth);

 SetColor(clRed);

 Line(0, 0, GetMaxX, GetMaxY);

 Line(GetMaxX, 0, 0, GetMaxY);

 SetColor(clWhite);

 Rectangle(0, 0, GetMaxX, GetMaxY);

 // scroll the screen left

 for i := 0 to (SX - 640) div 4 do

 SetScreenStart(i * 4, 0, True);

 // scroll the screen up

 for i := 0 to (SY - 480) div 4 do

 SetScreenStart(SX - 640, i * 4, True);

 // scroll the screen right

 for i := (SX - 640) div 4 downto 0 do

 SetScreenStart(i * 4, SY - 480, True);

 // scroll the screen down

 for i := (SY - 480) div 4 downto 0 do

 SetScreenStart(0, i * 4, True);

 // Wait a key

 ReadKey;

// Close Graph and restore old video mode

 CloseGraph;

end.


SetNormalMode procedure

Graph Unit

Cancels action of procedure SetVirtualMode and re-directs graphic operations to active graphic page.

Declaration:

procedure SetNormalMode

See also: SetVirtualMode, FlipToMemory and FlipToScreen


SetPalette procedure

Graph Unit

Changes one palette color as specified by ColorNum and Color.

Declaration:

procedure SetPalette(ColorNum: Word; Color: Word);

Remarks:

Changes the ColorNum entry in the palette to Color. SetPalette (0, clLightCyan) makes the first color in the palette light cyan. ColorNum can range from 0 to 255 and works only in 256-colored (palette) modes. If an invalid input is passed to SetPalette, GraphResult returns a value of grError, and the palette remains unchanged.


SetRGBPalette procedure

Graph Unit

Modifies palette entries for the VGA, MCGA and 256-colored SVGA modes.

Declaration:

procedure SetRGBPalette(ColorNum, RedValue, GreenValue, BlueValue: Byte);

Remarks:

ColorNum defines the palette entry to be loaded, while RedValue, GreenValue, and BlueValue define the component colors of the palette entry.


SetScreenStart procedure

Graph Unit

Sets the CRTC display starting address to the specified value.

Declaration:

procedure SetScreenStart(X,Y: DWord; WaitForRetrace: Boolean);

Remarks:

You can use this procedure to implement hardware scrolling.  You can also use this function to perform double buffering. Keep in mind, that your video card may not support extended CRTC  addressing!

If the WaitForRetrace flag is False, the routine will not wait for a vertical retrace before programming the CRTC starting address. Otherwise the routine will sync to a vertical retrace.  Under VBE 1.2 it is not guaranteed what the behavior will be (some wait and some don't).


SetSVGAMode procedure

Graph Unit

Sets SVGA video mode with given resolution and color depth.

Declaration:

procedure SetSVGAMode(XRes, YRes, BPP, VMode: Word);

Remarks:

XRes and YRes parameters define required resolution; BPP define color depth (bits per pixel) and must be in range [8,15,16,24,32]. VMode parameter must be in range [1..3]:

  LFBorBanked        = 0 - Set Lfb or Banked modes.

  BankedOnly         = 1 - Set Banked modes only;

  LFBOnly            = 2 - Set Lfb modes only;

Example:

SetSVGAMode(640,480,8,LfbOrBanked) tortured to set 256-colored (8 bits per pixel) SVGA mode with resolution 640x480. This procedure will try to install Lfb mode, if it supported. If not - Banked mode will be installed.


SetTextJustify procedure

Graph Unit

Sets text justification values used by OutText and OutTextXY.

Declaration:

procedure SetTextJustify(Horiz, Vert: DWord);

Remarks:

Text output after a SetTextJustify will be justified around the current pointer in the manner specified. Given the following,

 SetTextJustify(CenterText, CenterText);

 OutTextXY(100, 100, 'ABC');

The point (100, 100) will appear in the middle of the letter B. The default justification settings can be restored by SetTextJustify (LeftText, TopText). If an invalid input is passed to SetTextJustify, GraphResult returns a value of grError, and the current text justification settings will be unchanged.


SetTextStyle procedure

Graph Unit

Sets style for text output in graphics mode.

Declaration:

procedure SetTextStyle(Font, Direction: DWord);


SetSplineSteps procedure
SetSplineLineSteps procedure

Graph Unit

Adjusts smoothing factor used to draw the spline.

Declaration:

procedure SetSplineSteps(Steps: DWord);

Remarks:

By default smoothing factor (Steps value) = 30. See Spline procedure.


SetTranspMode procedure

Graph Unit

Sets/resets transparent mode for BitMaps output.

Declaration:

procedure SetTranspMode(Mode: Boolean; Color: DWord);

Remarks:

TMT Graph supports transparent BitMaps blt. If Mode parameter is True, all pixels consisting of BitMap pixels with a color which is different from the given Color value will be put to the screen. Any pixel which coincides with the value Color will be ignored (will not be placed on the screen). This is very useful for games programming.  Transparent BitMaps blt are supported in any graphic mode (MCGA/VGA, SVGA 256, 32K, 64K, 16M and 16M+A colored modes, with LFB and banked modes)!

SetTranspMode affects calls to the following routines only: PutHTextel, PutSprite and PutImage.


SetViewPort procedure

Graph Unit

Sets the current output viewport or window for graphics output

Declaration:

procedure SetViewPort(X1, Y1, X2, Y2: Longint; Clip: Boolean);

Remarks:

(X1, Y1) defines the upper left corner of the viewport, and (X2, Y2) defines the lower right corner. The upper left corner of a viewport is (0, 0).

The Boolean parameter Clip determines whether drawings are clipped at the current viewport boundaries.

SetViewPort (0, 0, GetMaxX, GetMaxY, True)

always sets the viewport to the entire graphics screen.  If (X1>=X2) or (Y1>=Y2), GraphResult returns grError, and the current view settings will be unchanged. The TMT Graph unit allows the assignment of viewport outside the screen!

All graphics commands (for example: GetX, OutText, Line and so on) are viewport-relative.

If the Boolean parameter Clip is set to True when a call to SetViewPort is made, all drawings will be clipped to the current viewport.  Note that the current pointer is never clipped.  The following will not draw the whole line requested because the line will be clipped to the current viewport:

 SetViewPort(10, 10, 20, 20, ClipOn);

 Line(0, 5, 15, 5);

The line would start at absolute coordinates (10,15) and terminate at absolute coordinates (25, 15) if no clipping were performed. But because clipping was performed, the actual line drawn would start at absolute coordinates (10, 15) and terminate at coordinates (20, 15). SetSVGAMode, GraphDefaults, and SetGraphMode all reset the viewport to the entire graphics screen. The current viewport settings are available by calling the procedure GetViewSettings, which accepts a parameter of ViewPortType.

SetViewPort moves the current pointer to (0, 0).


SetVirtualMode procedure

Graph Unit

Sets virtual graphic mode.

Declaration:

procedure SetVirtualMode(BuffAddr: Pointer)

Remarks:

This procedure re-directs all graphic operations directly to the virtual video buffer pointed to by BuffAddr in the memory. You must previously allocate a memory block for the virtual buffer using GetMem procedure. Use GetPageSize to obtain the size of the video page to be allocated.

See also: SetNormalMode, FlipToScreen and FlipToMemory


SetVisualPage procedure

Graph Unit

Sets the visual graphics page number.

Declaration:

procedure SetVisualPage(Page: DWord; WaitForRetrace: Boolean);

Remarks:

Makes Page the visual graphics page.

Multiple pages are supported only by the SVGA graphics modes. With multiple graphics pages, a program can direct graphics output to an offscreen page, then quickly display the offscreen image by changing the visual page with the SetVisualPage procedure.  This technique is especially useful for animation.  If the WaitForRetrace flag is not True, this routine will not sync to the vertical retrace.  This flag is now part of the VBE 2.0 spec, and if you have a VBE 1.2 device you cannot be sure that the device will sync to the retrace anyway.


SetWriteMode procedure

Graph Unit

Sets the writing mode for line drawing.

Declaration:

procedure SetWriteMode(WriteMode: DWord);

Remarks:

Each binary operation constant corresponds to a binary operation between each byte in the line and the corresponding bytes on the screen. CopyPut uses the assembly language MOV instruction, overwriting the line with whatever is on the screen. XORPut uses the XOR command to combine the line with the screen.  Two successive XOR commands will erase the line and restore the screen to its original appearance.

SetWriteMode affects calls to the following routines only: DrawPoly, PutPixel, Line, LineRel, LineTo, Rectangle, Circle, Ellipse, Bar3D, PutHTextel, PutSprite, DrawEllipse, Triangle and PutImage.


Spline procedure

Graph Unit

Draws a spline.

Declaration:

procedure Spline(Nodes: Byte; Points: array of PointType);

Remarks:

Fits a smooth curve through a given set of points. Nodes specifies the number of Points.  A coordinate pair consists of two Longints, an X and a Y value.

Use the SetSplineLineSteps procedure to adjust the spline.


Stretch procedure

Graph Unit

Stretches screen vertical in Param times.

Declaration:

procedure Stretch(Param: Byte);


TextHeight function

Graph Unit

Returns the height of a string, in pixels.

Declaration:

function TextHeight(TextString: string): DWord;

Remarks:

Takes the current font size, and determines the height of the TextString in pixels. This is useful for adjusting the spacing between lines, computing viewport heights, sizing a title to make it fit on a graph or in a box, etc.

It is important to use TextHeight to compute the height of strings, instead of doing the computation manually. In that way, no source code modifications have to be made when different fonts are selected.


TextWidth function

Graph Unit

Returns the width of a string in pixels.

Declaration:

function TextWidth(TextString: string): DWord;

Remarks:

Takes the string length, current font size, and multiplication factor, and determines the width of TextString in pixels. This is useful for computing view-port widths, sizing a title to make it fit on a graph or in a box, and so on.

For example, with the 8x8 bit-mapped font (set by SetTextStyle), the string TMT is 24 pixels wide.

It is important to use TextWidth to compute the width of strings, instead of doing the computation manually. In that way, no source code modifications have to be made when different fonts are selected.


TotalVbeMemory function

Graph Unit

Returns size in bytes of total video memory.

Declaration:

function TotalVbeMemory: DWord;

Remarks:

If VESA VBE 1.1+ is not supported, this function will return zero.


TotalVbeModes function

Graph Unit

Returns the total number of supported VESA modes.

Declaration:

function TotalVbeModes: Word;

Remarks:

Use GetVbeModesList to get info on supported modes.


Triangle procedure

Graph Unit

Draws a triangle.

Declaration:

procedure Triangle(X1, Y1, X2, Y2, X3, Y3: Longint);

procedure Triangle(X1, Y1, X2, Y2, X3, Y3: Longint; Color: DWORD);


The Keyboard Unit

  The Keyboard unit contains 13 procedures and functions for advanced keyboard control.

Keyboard Unit Constants

Keyboard Unit Procedures and Functions


Keyboard Unit Constants

The following constants are defined in Keyboard Unit:

const

  ESC_Scan:     Byte = $01;      Ent_Scan:     Byte = $1c;

  Back_Scan:    Byte = $0e;      Rsh_Scan:     Byte = $36;

  Ctrl_Scan:    Byte = $1d;      Prt_Scan:     Byte = $37;

  Lsh_Scan:     Byte = $2a;      Alt_Scan:     Byte = $38;

  Caps_Scan:    Byte = $3a;      Home_Scan:    Byte = $47;

  F1_Scan:      Byte = $3b;      Up_Scan:      Byte = $48;

  F2_Scan:      Byte = $3c;      PgUp_Scan:    Byte = $49;

  F3_Scan:      Byte = $3d;      Min_Scan:     Byte = $4a;

  F4_Scan:      Byte = $3e;      Left_Scan:    Byte = $4b;

  F5_Scan:      Byte = $3f;      Mid_Scan:     Byte = $4c;

  F6_Scan:      Byte = $40;      Right_Scan:   Byte = $4d;

  F7_Scan:      Byte = $41;      Plus_Scan:    Byte = $4e;

  F8_Scan:      Byte = $42;      End_Scan:     Byte = $4f;

  F9_Scan:      Byte = $43;      Down_Scan:    Byte = $50;

  F10_Scan:     Byte = $44;      PgDn_Scan:    Byte = $51;

  F11_Scan:     Byte = $d9;      Ins_Scan:     Byte = $52;

  F12_Scan:     Byte = $da;      Del_Scan:     Byte = $53;

  Scrl_Scan:    Byte = $46;      Num_Scan:     Byte = $45;

  Tab_Scan:     Byte = $0f;      Space_Scan:   Byte = $39;


Keyboard Unit Procedures and Functions

AsciiToScan

GetKey

FlushKeyboard

MultikeysDone

MultikeysInit

ScanToAscii

TestAlt

TestCapsLock

TestCtrl

TestNumLock

TestScrollLock

TestShift

TestKey


AsciiToScan function
AsciiToScan

Keyboard Unit

Translates a given OEM ASCII character into the scan code.

Declaration:

function AsciiToScan(AsciiChar: Char): Byte;

See also:

ScanToAscii


GetKey function
GetKey

Keyboard Unit

Returns a character and an extended scan code.

Declaration:

function GetKey: WORD;

Remarks:

The GetKey function returns the character code in its low-order byte (LoByte(GetKey)) and the extended scan code in its high-order byte (HiByte(GetKey)).


FlushKeyboard procedure
FlushKeyboard

Keyboard Unit

Flushes all contents of the keyboard buffer.

Declaration:

procedure FlushKeyboard;

Win32 console target:

The FlushKeyboard procedure flushes the console input buffer. All input records currently in the input buffer are discarded.


MultikeysDone procedure
MultikeysDone

Keyboard Unit

Stops a multi-keys mode.

Declaration:

procedure MultikeysDone

See also:

MultikeysInit


MultikeysInit procedure
MultikeysInit

Keyboard Unit

Initializes a multi-keys mode.

Declaration:

procedure MultikeysInit;

Remarks:

The multi-keys mode allow one to control the state of simultaneously pressed keys.

See also:

MultikeysDone

GetKey


ScanToAscii function
ScanToAscii

Keyboard Unit

Translates a given scan code into the OEM ASCII character.

Declaration:

function ScanToAscii(ScanCode: Byte): Char;

Remarks:

The ScanToAscii function returns the OEM ASCII character in uppercase.

See also:

AsciiToScan


TestAlt function
TestAlt

Keyboard Unit

Returns TRUE if the ALT key is pressed, FALSE otherwise.

Declaration:

function TestAlt: Boolean;


TestCapsLock function
TestCapsLock

Keyboard Unit

Returns TRUE if the CAPS LOCK light is on, FALSE otherwise.

Declaration:

function TestCapsLock: Boolean;


TestCtrl function
TestCtrl

Keyboard Unit

Returns TRUE if the CTRL key is pressed, FALSE otherwise.

Declaration:

function TestCtrl: Boolean;


TestNumLock function
TestNumLock

Keyboard Unit

Returns TRUE if the NUM LOCK light is on, FALSE otherwise.

Declaration:

function TestNumLock: Boolean;


TestScrollLock function
TestScrollLock

Keyboard Unit

Returns TRUE if the SCROLL LOCK light is on, FALSE otherwise.

Declaration:

function TestScrollLock: Boolean;


TestShift function
TestShift

Keyboard Unit

Returns TRUE if the SHIFT key is pressed, FALSE otherwise.

Declaration:

function TestShift: Boolean;


TestKey function
TestKey

Keyboard Unit

Checks the state of a key with a given scan code.

Declaration:

function TestKey(Scan: Byte): Boolean;

Remarks:

The TestKey function returns TRUE if the key with the given scan code is pressed, FALSE otherwise. This function works in multi-keys mode only (see MultikeysInit).

Example:

uses Keyboard;

begin

  MultikeysInit;

  Writeln('Press [Esc]+[Space] to exit..');

  repeat

    (* Wait loop *)

  until (TestKey(Space_Scan) and TestKey(Esc_Scan));

  Writeln('Ok.');

  MultikeysDone;

end.


The Math Unit

Math Unit Constants

Math Unit Procedures and Functions


Math Unit Constants

Following constants are defined in the Math unit

MinSingle   = 1.5E-45;

MaxSingle   = 3.4E+38;

MinDouble   = 5.0E-324;

MaxDouble   = 1.7E+308;

MaxExtended = MaxDouble;

MinExtended = MinDouble;

HalfLnMax   = 3.54863405227661E+0002;

Deg2Rad     = 1.74532925199433E-0002;

Rad2Deg     = 5.72957795130823E+0001;

Grad2Rad    = 1.57079632679490E-0002;

Rad2Grad    = 6.36619772367581E+0001;

DoublePI    = 6.28318530717959E+0000;

e           = 2.71828182845905E+0000;


Math Unit Procedures and Functions

ArcCos

ArcCosH

ArcCotan

ArcCotanH

ArcCsc

ArcCscH

ArcSec

ArcSecH

ArcSin

ArcSinH

ArcTan2

Ceil

CelsToFahr

CmToInch

CosH

Cotan

Csc

CscH

Cterm

CycleToRad

DeltaPercent

DegToRad

Evaluate procedure

FahrToCels

Floor

Fv

GalToLitre

GradToRad

Hypot

InchToCm

KgToLb

LbToKg

LitreToGal

Log10

Log2

LogN

Max

Min

Npv

Percent

Pmt

Power

Pv

RadToCycle

RadToDeg

RadToGrad

Rate

Sec

SecH

Sgn

SinH

Sln

Syd

Tan

TanH

Term


ArcCos function

Math Unit

Calculates the inverse cosine of the given number.

Declaration:

function ArcCos(X: Extended): Extended;


ArcCosH function

Math Unit

Calculates the inverse hyperbolic cosine of the given number.

Declaration:

function ArcCosH(X: Extended): Extended;


ArcCotan function

Math Unit

Calculates the inverse cotangent of the given number.

Declaration:

function ArcCotan(X: Extended): Extended;


ArcCotanH function

Math Unit

Calculates the inverse hyperbolic cotangent of the given number.

Declaration:

function ArcCotanH(X: Extended): Extended;


ArcCsc function

Math Unit

Calculates the inverse cosecant of the given number.

Declaration:

function ArcCsc(X: Extended): Extended;


ArcCscH function

Math Unit

Calculates the inverse hyperbolic cosecant of the given number.

Declaration:

function ArcCscH(X: Extended): Extended;


ArcSec function

Math Unit

Calculates the inverse secant of the given number.

Declaration:

function ArcSec(X: Extended): Extended;


ArcSecH function

Math Unit

Calculates the inverse hyperbolic secant of the given number.

Declaration:

function ArcSecH(X: Extended): Extended;


ArcSin function

Math Unit

Calculates the inverse sine of the given number.

Declaration:

function ArcSin(X: Extended): Extended;


ArcSinH function

Math Unit

Calculates the inverse hyperbolic sine of the given number.

Declaration:

function ArcSinH(X: Extended): Extended;


ArcTan2 function

Math Unit

Calculates the arctangent angle and quadrant of the given number.

Declaration:

function ArcTan2(Y, X: Extended): Extended;

Remarks:

The ArcTan2 function calculates ArcTan(Y/X), and returns an angle in the correct quadrant. The values of X and Y must be between -264 and 264. X can not be 0. The return value will fall in the range from -Pi to Pi radians.


ArcTanH function

Math Unit

Calculates the inverse hyperbolic tangent of the given number.

Declaration:

function ArcTanH(X: Extended): Extended;


Ceil function

Math Unit

Rounds variables up toward positive inifinity.

Declaration:

function Ceil(X: Extended): Extended;

function Ceil(X: Extended): Longint;

Remarks:

Use Ceil to obtain the lowest integer greater than or equal to X.


CelsToFahr function

Math Unit

Converts Celsius to Fahrenheit.

Declaration:

function CelsToFahr(Celsius: Extended): Extended;

Remarks:

Use CelsToFahr to convert temperature measured in Celsius into Fahrenheit. CelsToFahr uses the formula

Celsius * 9.0 / 5.0 + 32.0


CmToInch function

Math Unit

Converts centimetres to inches.

Declaration:

function CmToInch(Cm: Extended): Extended;

Remarks:

Use CmToInch to convert length measured in centimetres into inches. CmToInch uses the formula

Cm / 2.54


CosH function

Math Unit

Calculates the hyperbolic cosine of given angle.

Declaration:

function CosH(Angle: Extended): Extended;

Remarks:

Use the CosH function to calculate the hyperbolic cosine of X.


Cotan function

Math Unit

Returns the cotangent of Angle in radians.

Declaration:

function Cotan(Angle: Extended): Extended;

Remarks:

Cotan(Angle) = Cos(Angle) / Sin(Angle).


Csc function

Math Unit

Returns the cosecant of Angle in radians.

Declaration:

function Csc(Angle: Extended): Extended;

Remarks:

Csc(Angle) = 1 / Sin(Angle).


CscH function

Math Unit

Returns the hyperbolic cosecant of Angle in radians.

Declaration:

function CscH(Angle: Extended): Extended;


Cterm function

Math Unit

Returns the number of compounding periods.

Declaration:

function Cterm(Rate: Extended; FutureValue, PresentValue: Extended): Extended;


CycleToRad function

Math Unit

Converts an angle measurement from cycles to radians

Declaration:

function CycleToRad(Cycle: Extended): Extended;

Remarks:

Use CycleToRad to convert angles measured in cycles into radians. CycleToRad uses the formula

Cycle * 2 * PI


DeltaPercent function

Math Unit

Compute percent deviation.

Declaration:

function DeltaPercent(Value1, Value2: Extended): Extended;

Remarks:

The DeltaPercent returns deviation between Value2 percent (%) from Value1. Result is lower than 1.


DegToRad function

Math Unit

Returns the value of a degree measurement expressed in radians.

Declaration:

function DegToRad(Degrees: Extended): Extended;

Remarks:

Use DegToRad to convert angles expressed in degrees to the corresponding value in radians. DegToRad uses the formula

Degrees * PI / 180


Evaluate procedure

Math Unit

Evaluates the given expression.

Declaration:

procedure Evaluate(Expr: String; var Result: Extended; var ErrCode: Longint);

Remarks:

Use Evaluate to evaluate any valid expression given in Expr. The Result variable returns the evaluated expression. If it succeeds, the ErrCode variable is 0.

Examples:

uses Math, Strings;

const

  Expr = 'cos(0)*(5^2-3.1)';

var

  Result: Extended;

  ErrCode: Longint;

begin

  Evaluate(Expr, Result, ErrCode);

  if ErrCode = 0 then

    Writeln(Expr, ' = ', Fls(Result))

  else

    Writeln('Invalid expression');

end.

The example above will print 21.9.


FahrToCels function

Math Unit

Converts Fahrenheit to Celsius.

Declaration:

function FahrToCels(Fahr: Extended): Extended;

Remarks:

Use FahrToCels to convert temperature measured in Fahrenheit into Celsius. FahrToCels uses the formula

(Fahr - 32.0) * 5.0 / 9.0


Floor function

Math Unit

Rounds variables toward negative infinity.

Declaration:

function Floor(X: Extended): Extended;

function Floor(X: Extended): Longint;

Remarks:

Use Floor to obtain the highest integer less than or equal to X.


Fv function

Math Unit

Calculates the Future Value.

Declaration:

function Fv(Payment: Extended; Rate: Extended; Term: DWord): Extended;


GalToLiters function
GalToLitre function

Math Unit

Converts US gallons to litres.

Declaration:

function GalToLitre(Gallons: Extended): Extended;

Remarks:

Use GalToLitre to convert volume measured in gallons into litres. GalToLitre uses the formula:

Gallons * 3.785411784


GradToRad function

Math Unit

Converts grads to radians.

Declaration:

function GradToRad(Grad: Extended): Extended;

Remarks:

The GradToRad function converts angles of grad measure into radians. GradToRad uses the formula

Grad * PI / 200


Hypot function

Math Unit

Calculates the length of the hypotenuse.

Declaration:

function Hypot(X, Y: Extended): Extended;

Remarks:

The Hypot function returns the length of the hypotenuse of a right triangle. Specify the lengths of the sides adjacent to the right angle as X and Y. Hypot uses the formula:


InchToCm function

Math Unit

Converts inches to centimetres.

Declaration:

function InchToCm(Inches: Extended): Extended;

Remarks:

Use InchToCm to convert length measured in inches into centimetres. InchToCm uses the formula

Inches * 2.54


KgToLb function

Math Unit

Converts kilograms to pounds.

Declaration:

function KgToLb(Kilograms: Extended): Extended;

Remarks:

Use KgToLb to convert weight measured in kilograms into pounds. KgToLb uses the formula

Kg / 0.45359237


LbToKg function

Math Unit

Converts pounds to kilograms.

Declaration:

function LbToKg(Pounds: Extended): Extended;

Remarks:

Use LbToKg to convert weight measured in pounds into kilograms. LbToKg uses the formula

Pounds * 0.45359237


LitersToGal function
LitreToGal function

Math Unit

Converts litres to US gallons.

Declaration:

function LitreToGal(Litre: Extended): Extended;

Remarks:

Use LitreToGal to convert volume measured in litres into gallons. LitreToGal uses the formula

Litre / 3.785411784


Log10 function

Math Unit

Calculates log base 10.

Declaration:

function Log10(X: Extended): Extended;

Remarks:

The Log10 function returns the log (base 10) of X.


Log2 function

Math Unit

Calculates log base 2.

Declaration:

function Log2(X: Extended): Extended;

Remarks:

The Log2 function returns the log (base 2) of X.


LogN function

Math Unit

Calculates log with a specified base.

Declaration:

function LogN(Base, X: Extended): Extended;

Remarks:

The LogN function returns the log (with specified base) of X.


Max function

Math Unit

Returns the greater of two numeric values.

Declaration:

function Max(A, B: Longint): Longint;

function Max(A, B: Single): Single;

function Max(A, B: Double): Double;

function Max(A, B: Extended): Extended;

Remarks:

Use Max to compare two numeric values. Max returns the greater value of the two.


Min function

Math Unit

Returns the smaller of two numeric values.

Declaration:

function Min(A, B: Longint): Longint;

function Min(A, B: Single): Single;

function Min(A, B: Double): Double;

function Min(A, B: Extended): Extended;

Remarks:

Use Min to compare two numeric values. Min returns the smaller value of the two.


Npv function

Math Unit

Calculates the Net Present Value.

Declaration:

function Npv(Rate: Extended; Series: array of Double): Extended;


Percent function

Math Unit

Compute percent (%).

Declaration:

function Percent(Value1, Value2: Extended): Extended;

Remarks:

The Percent returns Value2 percent (%) from Value1. Percent uses the formula:

100 * Value2 / Value1


Pmt function

Math Unit

Calculates a fully amortized payment.

Declaration:

function Pmt(Principal: Extended; Rate: Extended; Term: DWord): Extended;


Power function

Math Unit

Raises Base to any power specified.

Declaration:

function Power(Base, Exponent: Extended): Extended;

function Power(Base: Extended; Exponent: Longint): Extended;

Remarks:

The Power function raises Base to any power by Exponent parameter. Base must be a positive real number or an integer.


Pv function

Math Unit

Calculates the Present value.

Declaration:

function Pv(Payment: Extended; Rate: Extended; Term: DWord): Extended;


RadToCycle function

Math Unit

Converts radians to cycles.

Declaration:

function RadToCycle(Rad: Extended): Extended;

Remarks:

Use RadToCycle to convert angles measured in radians into cycles. RadToCycle uses the formula:

Rad / (2 * PI)


RadToDeg function

Math Unit

Returns the value of a radian measurement expressed in degrees.

Declaration:

function RadToDeg(Rad: Extended): Extended;

Remarks:

Use RadToDeg to convert angles measured in radians to degrees. RadToDeg uses the formula:

Rad * 180 / PI


RadToGrad function

Math Unit

Converts radians to grads.

Declaration:

function RadToGrad(Rad: Extended): Extended;

Remarks:

The RadToGrad function converts angles of radian measure into grads. RadToGrad uses the formula:

Rad * 200.0 / PI


Rate function

Math Unit

Returns the periodic interest rate.

Declaration:

function Rate(FutureValue, PresentValue: Extended; Term: DWord): Extended;


Sec function

Math Unit

Returns the secant of Angle in radians.

Declaration:

function Sec(Angle: Extended): Extended;

Remarks:

Sec(Angle) = 1 / Cos(Angle).


SecH function

Math Unit

Returns the hyperbolic secant of Angle in radians.

Declaration:

function SecH(Angle: Extended): Extended;


Sgn function

Math Unit

Returns the sign of a variable.

Declaration:

function Sgn(X: Extended): Longint;

function Sgn(X: Longint): Longint;

Remarks:

Use Sgn to obtain the sign of X. For example:

Sgn(3.2) = 1

Sgn(-5)  = -1

Sgn(0)   = 0


SinH function

Math Unit

Calculates the hyperbolic sine of a given angle.

Declaration:

function SinH(Angle: Extended): Extended;

Remarks:

Use the SinH function to calculate the hyperbolic sine of X.


Sln function

Math Unit

Returns the straight-line depreciation allowance of an asset.

Declaration:

function Sln(InitialValue, Residue: Extended; Time: DWord): Extended;

Remarks:

The Sln function calculates the straight-line depreciation allowance for an asset over one period of its life. The function divides the InitialValue minus the Residue by the number of years of useful Time of the asset. InitialValue is the amount initially paid for the asset. Residue is the value of the asset at the end of its useful life.


Syd function

Math Unit

Returns the sum of the year digits depreciation.

Declaration:

function Syd(InitialValue, Residue: Extended; Period, Time: DWord): Extended;

Remarks:

The Syd function calculates depreciation amounts for an asset using an accelerated depreciation method. This allows for higher depreciation in the earlier years of an asset's life. InitialValue is the initial cost of the asset. Residue is the value of the asset at the end of its life expectancy. Time is the length of the asset's life expectancy. Period is the period for which to calculate the depreciation.


Tan function

Math Unit

Tan returns the tangent of Angle in radians.

Declaration:

function Tan(Angle: Extended): Extended;

Remarks:

Tan(Angle) = Sin(Angle) / Cos(Angle).


TanH function

Math Unit

Calculates the hyperbolic tangent of given angle.

Declaration:

function TanH(Angle: Extended): Extended;

Remarks:

Use the TanH function to calculate the hyperbolic tangent of X.


Term function

Math Unit

Returns the number of payments.

Declaration:

function Term(Payment: Extended; Rate: Extended; FutureValue: Extended): Extended;


The Mouse Unit

  The Mouse unit is a programming interface for controlling a mouse pointing. Included is the ability to define and install your own interrupt mouse driver. This driver is called whenever a button on the mouse is pressed or released or when the mouse is moved. It is also possible to poll for mouse movement.

The benefits of having an interrupt mouse driver is that mouse events can take place at any time; one doesn't have to wait for them. Polling for mouse events must occur within some type of loop where the status of the mouse is constantly checked. There are many benefits over polling for mouse events.

The Mouse unit gives a Pascal program access to the main mouse-support functions:

•	Determining the presence or absence of a mouse

•	Mouse cursor positioning

•	Getting information about the position and the button states

•	Installing a mouse-driven Pascal interrupt handler

Mouse Unit Procedures and Functions


Mouse Unit Procedures and Functions

ClearMouseHandler

DoneMouse

GetButtonCount

GetMouseInfo

GetMouseX

GetMouseY

HideMouse

InitMouse

LeftButtonPressed

MickyToText

MiddleButtonPressed

RightButtonPressed

SetMouseHandler

SetMousePos

SetMouseRange

ShowMouse

TextToMicky


ClearMouseHandler procedure

Removes the user's mouse interrupt handler.

Declaration:

procedure ClearMouseHandler;

See also:

SetMouseHandler


DoneMouse procedure

Does the following:

−	removes (hides) the mouse cursor;

−	frees the callback address for the mouse interrupt handler;

−	frees the stack for the mouse interrupt handlers;

−	resets internal variable ButtonCount to 0.

Declaration:

procedure DoneMouse;

See also:

InitMouse


GetButtonCount function

Returns a number of mouse buttons.

Declaration:

function GetButtonCount: DWord;

Remarks:

The GetButtonCount must be called after execution of InitMouse procedure.


GetMouseInfo procedure

Returns information about the position of the mouse cursor (X,Y) and the pressed buttons (ButtonMask).

Declaration:

procedure GetMouseInfo(var ButtonMask: Word; var X: Word; var Y: Word);

See also:

MickyToText


GetMouseX function

Returns X-position of the mouse cursor.

Declaration:

function GetMouseX: DWord;

See also:

MickyToText

GetMouseY


GetMouseY function

Returns Y-position of the mouse cursor.

Declaration:

function GetMouseY: DWord;

See also:

MickyToText

GetMouseX


HideMouse procedure

When mouse is present, makes its cursor invisible.

Declaration:

procedure HideMouse;

Remarks:

This function ignored under Win32.

See also:

ShowMouse


InitMouse procedure

Mouse Unit

Does the following:

•	Allocates a 4K stack for the user's mouse interrupt-driven procedure.

•	Determines the presence or absence of the mouse.

•	If mouse is present:

−	enables the mouse cursor (calls ShowMouse);

−	positions the cursor to the upper-left screen corner;

−	reserves the callback address for the users' interrupt-driven mouse procedure (regardless of whether it will get installed or not).

Declaration:

procedure InitMouse;

See also:

DoneMouse


LeftButtonPressed function

Returns True, if left mouse button is currently pressed.

Declaration:

function LeftButtonPressed: Boolean;

See also:

MiddleButtonPressed

RightButtonPressed


MickyToText function

Converts mouse coordinates into text mode coordinates.

Declaration:

function MickyToText(Coord: DWord): DWord;

See also:

TextToMicky

GetMouseX

GetMouseY

GetMouseInfo


MiddleButtonPressed function

Returns True, if middle mouse button is currently pressed.

Declaration:

function MiddleButtonPressed: Boolean;

See also:

LeftButtonPressed

RightButtonPressed


RightButtonPressed function

Returns True, if right mouse button is currently pressed.

Declaration:

function RightButtonPressed: Boolean;

See also:

LeftButtonPressed

MiddleButtonPressed


SetMouseHandler procedure

Installs a Pascal interrupt-driven user's mouse handler (Hnd).

Declaration:

procedure SetMouseHandler (Mask: DWord; Procedure Hnd (Mask, Buttons, X, Y, MovX, MovY: System.Word));

Remarks:

The Mask parameter defines the classes of the events that call the handler; its format corresponds to the function 0Ch (INT 33h). When Hnd is called the Mask parameter contains the mask with the event type that occurred; Buttons contain the mask of the currently pressed buttons; X and Y contain the cursor's absolute position, and MovX and MovY contain the relative (signed) change of the last cursor position [negative numbers mean left or down; positive mean right or up]. These values are given in mouse position units; to convert to symbols, they need to be divided by 8.

Using SetMouseHandler you can install several handlers with different masks without having to clear previous handlers.

Event Mask (events which you want sent to your handler)

bit 0 = mouse movement           (Mask = $01)

bit 1 = left button pressed      (Mask = $02)

bit 2 = left button released     (Mask = $04)

bit 3 = right button pressed     (Mask = $08)

bit 4 = right button released    (Mask = $10)

bit 5 = center button pressed    (Mask = $20)

bit 6 = center button released   (Mask = $40)

        all events:      Mask = 007fH

        disable handler: Mask = 0000H

See also:

ClearMouseHandler

Example:

program Test;

uses CRT, Mouse;

var

  isExit: Boolean := FALSE;

  X, Y:   DWord;

  star:   Word := $0F2A;

  space:  Word := $0F00;

procedure MyHnd(Mask, Buttons, X, Y, MovX, MovY: System.Word);

begin

  GotoXY(1, 2);

  Writeln('XPos = ', MickyToText(X),', YPos = ', MickyToText(Y), '  ');

end;

begin

 ClrScr;

 Writeln('Press Esc to exit');

 HideCursor;

 InitMouse;

 SetMouseHandler($FFFF, MyHnd);

 repeat

  X := MickyToText(GetMouseX) + 1;

  Y := MickyToText(GetMouseY) + 1;

  if (LeftButtonPressed) and (Y > 2) and (Y < 25) then

    WriteAttr (X, Y, Star, 1);

  if (RightButtonPressed) and (Y > 2) and (Y < 25) then

    WriteAttr (X, Y, Space, 1);

  if Keypressed then

    isExit := ReadKey = #27;

 until isExit;

 ShowCursor;

 DoneMouse;

end.


SetMousePos procedure

Positions the mouse cursor to the point (X,Y).

Declaration:

procedure SetMousePos(X, Y: DWord);

Remarks:

This function ignored under Win32.

See also:

SetMouseRange

TextToMicky


SetMouseRange procedure

Sets mouse moving range.

Declaration:

procedure SetMouseRange(MinX, MinY, MaxX, MaxY: DWord);

Remarks:

This function ignored under Win32.

See also:

TextToMicky


ShowMouse procedure

If mouse is present, makes its cursor visible.

Declaration:

procedure ShowMouse;

Remarks:

This function ignored under Win32.

See also:

HideMouse


TextToMicky function

Converts text mode coordinates into mouse coordinates.

Declaration:

function TextToMicky(Coord: DWord): DWord;

See also:

MickyToText

SetMousePos

SetMouseRange


The Printer Unit

  The Printer unit declares a text file called Lst and associates it with the LPT1 device.

var Lst : Text;

When you use the Printer unit, you don't need to declare, assign, open, and close a text file yourself when you use your printer from within a program.

Example:

uses Printer;

begin

  WriteLn(Lst, 'Your printer works properly!');

end.


The Strings Unit

The Strings unit provides procedures and functions to manipulate strings, encrypt and decrypt data, perform search and replace on strings and more. While the majority of the functions and procedures on Strings can be written with TMT Pascal, the ones in the Strings unit are all written in assembly language and thus have must faster execution times.

Strings Unit Overloaded Operators

Strings Unit Procedures and Functions


Strings Unit Overloaded Operators

The Strings unit overloads the following operators

overload  +:= = StrAppend

overload  +:= = StrAppendC

overload   *  = Dup_SI

overload   *  = Dup_CI


Strings Unit Procedures and Functions

Align

AnsiCompareStr

AnsiLowerCase

AnsiCompareText

AnsiStrComp

AnsiStrIComp

AnsiStrLComp

AnsiStrLIComp

AnsiStrLower

AnsiStrUpper

AnsiUpperCase

AppendPathDelimiter

Bin

Dup_CI

Dup_SI

Fix

FloatToStr

Fls

Flt

Hex

HexVal

IntToBin

IntToHex

IntToStr

IsDelimiter

IsPathDelimiter

IsValidIdent

LastDelimiter

LowerCase

QuotedStr

StrAppend

StrAppendC

StrCat

StrComp

StrCopy

StrDispose

StrECopy

StrEnd

StrLCat

StrIComp

StrLComp

StrLCopy

StrLen

StrLIComp

StrLower

StrMove

StrNew

StrPas

StrPCopy

StrPos

StrRScan

StrScan

StrToInt

StrToIntDef

StrUpper

Trim

TrimLeft

TrimRight

Uns

UpperCase

Whl


Align function

Strings Unit

Pads the argument up to width with spaces.

Declaration:

function Align(Str: String; Width: LongInt): String;

Remarks:

Spaces are on the right if width > 0, and on the left otherwise.


AnsiCompareStr function

Strings Unit

Compares strings based on the current Windows locale. It is case sensitive.

Declaration:

function AnsiCompareStr(S1, S2: String): Longint;

Remarks:

AnsiCompareStr compares S1 to S2, with case sensitivity. The return value is:

Condition       Return Value

S1 > S2	> 0

S1 < S2	< 0

S1 = S2	= 0


AnsiLowerCase function

Strings Unit

Converts a string to lower case.

Declaration:

function AnsiLowerCase(S: String): String;


AnsiCompareText function

Strings Unit

Compares strings based on the current Windows locale and is not case sensitive.

Declaration:

function AnsiCompareText(S1, S2: String): Longint;

Remarks:

AnsiCompareText compares S1 to S2, without case sensitivity. The compare operation is controlled by the current Windows locale. The return value is:

Condition       Return Value

S1 > S2	> 0

S1 < S2	< 0

S1 = S2	= 0


AnsiStrComp function

Strings Unit

Compares null-terminated character strings case sensitively.

Declaration:

function AnsiStrComp(S1, S2: PChar): Longint;

Remarks:

AnsiStrComp compares S1 to S2, with case sensitivity. The return value is:

Condition       Return Value

S1 > S2	> 0

S1 < S2	< 0

S1 = S2	= 0


AnsiStrIComp function

Strings Unit

Compares null terminated character strings case insensitively.

Declaration:

function AnsiIStrComp(S1, S2: PChar): Longint;

Remarks:

AnsiStrIComp compares S1 to S2, without case sensitivity. The return value is:

Condition       Return Value

S1 > S2	> 0

S1 < S2	< 0

S1 = S2	= 0


AnsiStrLComp function

Strings Unit

Compares the first MaxLen bytes of two character sequences. It is case-sensitively.

Declaration:

function AnsiStrLComp(S1, S2: PChar; MaxLen: DWord): Longint;

Remarks:

AnsiStrLComp compares S1 to S2, with case sensitivity. If S1 or S2 is longer than MaxLen bytes, AnsiStrLComp only compares the first MaxLen bytes. The return value is:

Condition       Return Value

S1 > S2	> 0

S1 < S2	< 0

S1 = S2	= 0


AnsiStrLIComp function

Strings Unit

Compares two strings, case-insensitively, up to the first MaxLen bytes.

Declaration:

function AnsiStrLIComp(S1, S2: PChar; MaxLen: DWord): Longint;

Remarks:

AnsiStrLIComp compares S1 to S2, without case sensitivity. If S1 or S2 is longer than MaxLen characters, AnsiStrLIComp only compares up to the first MaxLen characters. The return value is:

Condition       Return Value

S1 > S2	> 0

S1 < S2	< 0

S1 = S2	= 0


AnsiStrLower function

Strings Unit

Converts all characters in a null-terminated character sequence to lower case.

Declaration:

function AnsiStrLower(Str: PChar): PChar;

Remarks:

AnsiStrLower returns a null-terminated character sequence where all characters are lower case.


AnsiStrUpper function

Strings Unit

Converts all characters in a null-terminated character sequence to upper case.

Declaration:

function AnsiStrUpper(Str: PChar): PChar;

Remarks:

AnsiStrUpper returns a null-terminated character sequence where all characters are upper case.


AnsiUpperCase function

Strings Unit

Converts a string to upper case.

Declaration:

function AnsiUpperCase(S: String): String;


AppendPathDelimiter function

Strings Unit

Appends a path delimiter (\) to the specified path-string.

Declaration:

function AppendPathDelimiter(const S: String): String;

Example:

AppendPathDelimiter('C:\TMTPL');          // returns 'C:\TMTPL\'

AppendPathDelimiter('C:\TMTPL\SAMPLES\'); // returns 'C:\TMTPL\SAMPLES\'


Bin function

Strings Unit

Converts argument into standard binary 32-characters string.

Declaration:

function Bin(n: Longint): String[32];

Examples:

Bin($000000FF) = ‘00000000000000000000000011111111’

Bin(126479829) = ‘00000111100010011110110111010101’


Dup_CI function

Strings Unit

Creates the string by repeating character N times.

Declaration:

function Dup_CI(C: char; N: Longint): String;


Dup_SI function

Strings Unit

Copies the string N times.

Declaration:

function Dup_SI(C: String; N: Longint): String;


Fix function

Strings Unit

Converts argument into a fixed point string.

Declaration:

function Fix(X: Extended; W, Pr: LongInt): String[15];

Remarks:

Pr is the number of digits after the decimal point.


FloatToStr function

Strings Unit

Converts a floating point value to a string.

Declaration:

function FloatToStr(Value: Extended): String;

Remarks:

FloatToStr converts the floating-point value given by Value to its string representation.


Fls function

Strings Unit

Converts its argument into standard floating-point string.

Declaration:

function Fls(X: Extended): String;

Examples:

Fls(1E+1) = 10.

Fls(2.855E-2) = 0.02855


Flt function

Strings Unit

Converts its argument into a formatted floating-point string.

Declaration:

function Flt(X: Extended; W: Longint): String;


Hex function

Strings Unit

Converts its argument into a hex string.

Declaration:

function Hex(n: Longint): String[12];


HexVal function

Strings Unit

Converts a hex string into Longint.

Declaration:

function HexVal(const S: String): Longint;


IntToBin function

Strings Unit

Returns the bin representation of an integer.

Declaration:

function IntToBin(Value: Longint; Digits: DWord): String;

Remarks:

The IntToBin function converts a number into a string containing the number's binary (base 2) representation. Value is the number to convert. Digits indicates the number of binary digits to return.


IntToHex function

Strings Unit

Returns the hex representation of an integer.

Declaration:

function IntToHex(Value: Longint; Digits: DWord): String;

Remarks:

The IntToHex function converts a number into a string containing the number's hexadecimal (base 16) representation. Value is the number to convert. Digits indicates the number of hexadecimal digits to return.


IntToStr function

Strings Unit

Converts an integer to a string.

Declaration:

function IntToStr(Value: Longint): String;

Remarks:

The IntToStr function converts an integer into a string containing the decimal representation of that number. Value is the number to convert.


IsDelimiter function

Strings Unit

Returns TRUE if a specified character in a string matches one of a set of delimiters.

Declaration:

function IsDelimiter(const Delimiters, S: String; IndexPos: Longint): Boolean;


IsPathDelimiter function

Strings Unit

Returns TRUE if the byte at position IndexPos of a string is the backslash character (\).

Declaration:

function IsPathDelimiter(const S: String; IndexPos: Longint): Boolean;


IsValidIdent function

Strings Unit

Tests for a valid Pascal identifier.

Declaration:

function IsValidIdent(const Ident: String): Boolean;

Remarks:

IsValidIdent returns TRUE if the given string is a valid Pascal identifier. Identifiers are tokens that have a special meaning in TMT Pascal. Identifiers begin with a letter (A-Z or a-z) or underscore, and may contain letters, underscores, and digits (0-9).


LastDelimiter function

Strings Unit

Returns the byte index in S of the last character that matches any character in the Delimiters string.

Declaration:

function LastDelimiter(const Delimiters, S: String): Longint;

Example:

LastDelimiter('\.', 'C:\TMTPL\BIN\TMTPC.EXE');  // returns 19


LowerCase function

Strings Unit

Converts an ASCII string to lowercase.

Declaration:

function LowerCase(Str: String): String;

Remarks:

LowerCase returns a string with the same text as the string passed in Str, but with all letters converted to lowercase. The conversion affects only 7-bit ASCII characters between 'A' and 'Z'.


QuotedStr function

Strings Unit

Returns the quoted version of a string.

Declaration:

function QuotedStr(const S: String): String;

Remarks:

A quote character (') will be inserted at the beginning and end of S, and each single quote character in the string is repeated.


StrAppend procedure

Strings Unit

Appends Src at the end of Dst.

Declaration:

procedure StrAppend(var Dst: String; const Src: String);


StrAppendC procedure

Strings Unit

Appends character Src to the end of string Dst.

Declaration:

procedure StrAppendC(var Dst: String; Src: Char);


StrCat function

Strings Unit

StrCat appends Src to the end of Dst and returns the concatenated string of PChar type.

Declaration:

function StrCat(Dst, Src: PChar): PChar;


StrComp function

Strings Unit

StrComp compares S1 to S2

Declaration:

function StrComp(S1, S2 : PChar): Longint;

Remarks:

The return value is:

Condition       Return Value

S1 > S2	> 0

S1 < S2	< 0

S1 = S2	= 0


StrCopy function

Strings Unit

Copies Src string to the Dst.

Declaration:

function StrCopy(Dst, Src: PChar): PChar;


StrDispose procedure

Strings Unit

StrDispose disposes of a string allocated by StrNew.

Declaration:

procedure StrDispose(Str: PChar);


StrECopy function

Strings Unit

StrECopy copies Src to Dst and returns a pointer to the null character at the end of Dst.

Declaration:

function StrECopy(Dst, Src: PChar): PChar;


StrEnd function

Strings Unit

StrEnd returns a pointer to the end of a null terminated string.

Declaration:

function StrEnd(Str: PChar): PChar;

Remarks:

The StrEnd function returns a pointer to the null character at the end of Str.


StrLCat function

Strings Unit

StrLCat appends a specified maximum number of characters to specified string.

Declaration:

function StrLCat(Dst, Src: PChar; MaxLen: Longint): PChar;


StrIComp function

Strings Unit

StrIComp compares S1 to S2 without case sensitivity.

Declaration:

function StrIComp(S1, S2:PChar): Longint;

Remarks:

The return value is:

Condition       Return Value

S1 > S2	> 0

S1 < S2	< 0

S1 = S2	= 0


StrLComp function

Strings Unit

StrLComp compares a specified maximum number of characters (MaxLen) in two strings of PChar type.

Declaration:

function StrLComp(Str1, Str2: PChar; MaxLen: Longint): Longint;

Remarks:

The return value is:

Condition       Return Value

S1 > S2	> 0

S1 < S2	< 0

S1 = S2	= 0


StrLCopy function

Strings Unit

StrLCopy copies a specified maximum number of characters from Src to Dst.

Declaration:

function StrLCopy(Dst, Src: PChar; MaxLen: Longint): PChar;

Remarks:

The StrLCopy function copies MaxLen characters from Src to Dst and returns pointer on Dst.


StrLen function

Strings Unit

StrLen returns number of character in a string excluding the null terminator.

Declaration:

function StrLen(Str: PChar): LongInt;

Remarks:

The StrLen function calculates the number of characters in Str. The null terminator is not included.


StrLIComp function

Strings Unit

StrLIComp compares two strings up to a specified maximum number (MaxLen) of characters, not case sensitive.

Declaration:

function StrLIComp(Str1, Str2: PChar; MaxLen: Longint): Longint;

Remarks:

The return value is:

Condition       Return Value

S1 > S2	> 0

S1 < S2	< 0

S1 = S2	= 0


StrLower function

Strings Unit

The StrLower function returns a string in lower case.

Declaration:

function StrLower(Str: PChar): PChar;


StrMove function

Strings Unit

StrMove copies specified number of characters to the null terminated string.

Declaration:

function StrMove(Dst, Src: PChar; Count: LongInt): PChar;

Remaks:

The StrMove function copies Count characters from Src to Dst and returns pointer on Dst.


StrNew function

Strings Unit

The StrNew function allocates space on and copies a string to the heap; returns a pointer to the string.

Declaration:

function StrNew(Str: PChar): PChar;


StrPas function

Strings Unit

StrPas converts null-terminated (PChar) string Str to a Pascal-style string.

Declaration:

function StrPas(Str: PChar): String;


StrPCopy function

Strings Unit

StrPCopy copies Pascal-style string Src to a null-terminated (PChar) string Dst.

Declaration:

function StrPCopy(Dst: PChar; const Src: String): PChar;


StrPos function

Strings Unit

Finds first entry of Str2 in Str1.

Declaration:

function StrPos(Str1, Str2: PChar): PChar;

Remarks:

StrPos returns a pointer to the first entry of Str2 in Str1.


StrRScan function

Strings Unit

StrRScan returns a pointer to the last occurrence of Chr in Str.

Declaration:

function StrRScan(Str: PChar; Chr: Char): PChar;

Remarks:

The StrRScan function returns a pointer to the first entry of Chr in Str from end of Str. If Chr is not found Str, StrRScan returns nil.


StrScan function

Strings Unit

StrScan returns a pointer to first occurrence of a specified character in a string of PChar type.

Declaration:

function StrScan(Str: PChar; Chr: Char): PChar;

Remarks:

If Chr does not found in Str, StrScan returns nil.


StrToInt function

Strings Unit

Converts a string representing a long integer to a number.

Declaration:

function StrToInt(const S: String): Longint;

Examples:

StrToInt('11')  = 11;

StrToInt('$FF') = 256;


StrToIntDef function

Strings Unit

Converts a string representing a long integer to a number.

Declaration:

function StrToIntDef(const S: String; Default: Longint): Longint;

Remarks:

If S is not a valid number, StrToIntDef returns the number passed in Default.


StrUpper function

Strings Unit

The StrUpper function returns a string in upper case.

Declaration:

function StrUpper(Str: PChar): PChar;


Trim Function

Strings Unit

Trims a string of leading and trailing spaces and control characters.

Declaration:

function Trim(const S: String): String;


TrimLeft Function

Strings Unit

Trims string of leading spaces and control characters.

Declaration:

function TrimLeft(const S: String): String;


TrimRight Function

Strings Unit

Trims string of trailing spaces and control characters.

Declaration:

function TrimRight(const S: String): String;


Uns function

Strings Unit

Converts its argument into a sting unsigned integer.

Declaration:

function Uns(N: DWord): String[12];


UpperCase function

Strings Unit

Converts an ASCII string to uppercase.

Declaration:

function UpperCase(Str: String): String;

Remarks:

UpperrCase returns a string with the same text as the string passed in Str, but with all letters converted to uppercase. The conversion affects only 7-bit ASCII characters between 'a' and 'z'.


Whl function

Strings Unit

Converts the argument into signed integer.

Declaration:

function Whl(N: LongInt): String[12];


The System Unit

  The System unit provides low level support routines such as low level file I/O, heap management, a random number generator, string handling and more. The system unit is automatically linked with every program and need not be stated in a Uses statement.

Keep in mind, that the System unit always uses the FPU for floating point arithmetic.

System Unit Variables

System Unit Procedures and Functions


System Unit Variables
System Unit Constants and Variables

_environ

_psp

_zero

ErrorAddr

ExeName

ExeSize

ExitCode

ExitProc

FarPointer

FileMode

HeapHandle

InOutRes

Input

IsConsole

IsLibrary

LongRec

MaxCardinal

MaxDWord

MaxInt

MaxLongint

MaxWord

Output

RandSeed

Test8086

Test8087


_environ variable

System Unit

The _environ variable contains the environment address.

Declaration:

var _environ: Pointer;


_psp variable

System Unit

The _psp variable contains the logical 32-bit address of the PSP of the program.

Declaration:

var _psp: Pointer;


_zero variable

System Unit

The _zero variable is always 0 and provided for compatibility with old versions of TMT Pascal compiler.

Declaration:

var _zero: DWord := 0;


ErrorAddr variable

System Unit

ExitProc, ExitCode, and ErrorAddr variables are used to implement exit procedures.

The ExitProc pointer variable allows one to install an exit procedure. The exit procedure always gets called as part of a program's termination.

An exit procedure takes no parameters and must be compiled with a far procedure directive to force it to use the far call model.

When implemented properly, an exit procedure actually becomes part of a chain of exit procedures. The procedures on the exit chain get executed in reverse order of installation.

To keep the exit chain intact, you must save the current contents of ExitProc before changing it to the address of your own exit procedure.

The first statement in your exit procedure must reinstall the saved value of ExitProc.

An exit procedure may learn the cause of termination by examining the ExitCode integer variable and the ErrorAddr pointer variable.

 - In case of normal termination, ExitCode is 0 and ErrorAddr is nil.

 - In case of termination through a call to Halt, ExitCode contains the

   value passed to Halt and ErrorAddr is nil.

 - In case of termination due to a run-time error, ExitCode contains the

   error code and ErrorAddr contains the address of the statement in error.

The last exit procedure (the one installed by the run-time library) closes the Input and Output files. If ErrorAddr is not nil, it outputs a run-time error message.


ExeName variable

System Unit

The ExeName variable contains a pointer to a null-terminated string that contains the name of program (executable file).

Declaration:

var ExeName: PChar;


ExeSize variable

System Unit

The ExeSize variable contains the size of the program (executable file).

Declaration:

var ExeSize: DWord;


ExitCode variable

System Unit

ExitProc, ExitCode, and ErrorAddr variables are used to implement exit procedures.

The ExitProc pointer variable allows one to install an exit procedure. The exit procedure always gets called as part of a program's termination.

An exit procedure takes no parameters and must be compiled with a far procedure directive to force it to use the far call model.

When implemented properly, an exit procedure actually becomes part of a chain of exit procedures. The procedures on the exit chain get executed in reverse order of installation.

To keep the exit chain intact, you must save the current contents of ExitProc before changing it to the address of your own exit procedure.

The first statement in your exit procedure must reinstall the saved value of ExitProc.

An exit procedure may learn the cause of termination by examining the ExitCode integer variable and the ErrorAddr pointer variable.

 - In case of normal termination, ExitCode is 0 and ErrorAddr is nil.

 - In case of termination through a call to Halt, ExitCode contains the

   value passed to Halt and ErrorAddr is nil.

 - In case of termination due to a run-time error, ExitCode contains the

   error code and ErrorAddr contains the address of the statement in error.

The last exit procedure (the one installed by the run-time library) closes the Input and Output files. If ErrorAddr is not nil, it outputs a run-time error message.


ExitProc variable

System Unit

ExitProc, ExitCode, and ErrorAddr variables are used to implement exit procedures.

The ExitProc pointer variable allows one to install an exit procedure. The exit procedure always gets called as part of a program's termination.

An exit procedure takes no parameters and must be compiled with a far procedure directive to force it to use the far call model.

When implemented properly, an exit procedure actually becomes part of a chain of exit procedures. The procedures on the exit chain get executed in reverse order of installation.

To keep the exit chain intact, you must save the current contents of ExitProc before changing it to the address of your own exit procedure.

The first statement in your exit procedure must reinstall the saved value of ExitProc.

An exit procedure may learn the cause of termination by examining the ExitCode integer variable and the ErrorAddr pointer variable.

 - In case of normal termination, ExitCode is 0 and ErrorAddr is nil.

 - In case of termination through a call to Halt, ExitCode contains the

   value passed to Halt and ErrorAddr is nil.

 - In case of termination due to a run-time error, ExitCode contains the

   error code and ErrorAddr contains the address of the statement in error.

The last exit procedure (the one installed by the run-time library) closes the Input and Output files. If ErrorAddr is not nil, it outputs a run-time error message.


FarPointer type

System Unit

Declaration:

type FarPointer = record

   Ofs: Pointer;

   Seg: Word

end;

Remarks

FarPointer type used by SetIntVec and GetIntVec procedures.


FileMode variable

System Unit

The FileMode variable determines the access code to pass to Operating System when typed and untyped files are opened using the Reset procedure. By default FileMode is 2. Following modes may be assigned to FileMode:

  0   Read only

  1   Write only

  2   Read/Write


InOutRes variable

System Unit

The built-in I/O routines use InOutRes to store the value that the next call to the IOResult standard function will return.


Input variable

System Unit

Input and Output are the standard I/O files required by every Pascal implementation.


IsConsole variable

System Unit

IsConsole variable is always TRUE.

Declaration:

  var IsConsole: Boolean;


IsLibrary variable

System Unit

IsLibrary variable is always FALSE.

Declaration:

  var IsLibrary: Boolean;


LongRec type

System Unit

Declaration:

type

  LongRec = record

    Lo, Hi: Word;

  end;


MaxCardinal constant

System Unit

The maximum value of the Cardinal data type.

Declaration:

const MaxCardinal = High(Cardinal);

MaxCardinal represents the highest value in the range of the Cardinal data type (4294967295).


MaxDWord constant

System Unit

The maximum value of the DWord data type.

Declaration:

const MaxDWord = High(DWord);

MaxDWord represents the highest value in the range of the DWord data type (4294967295).


MaxInt constant

System Unit

The maximum value of the Integer data type.

Declaration:

const MaxInt = High(Integer);

MaxInt represents the highest value in the range of the Integer data type (32767).


MaxLongint constant

System Unit

The maximum value of the Longint data type.

Declaration:

const MaxLongint = High(Longint);

const MaxLong = High(Longint);

MaxLongint represents the highest value in the range of the Integer data type (2147483647).


MaxWord constant

System Unit

The maximum value of the Word data type.

Declaration:

const MaxWord = High(Word);

MaxWord represents the highest value in the range of the Integer data type (65535).


Output variable

System Unit

Input and Output are the standard I/O files required by every Pascal implementation.


RandSeed variable

System Unit

RandSeed stores the built-in random number generator's seed. By assigning a specific value to RandSeed, the Random function can be made to repeatedly generate a specific sequence of random numbers.

This is useful for applications that deal with data encryption, statistics, and simulations.


Test8086 variable

System Unit

Identifies the type of 80x86 processor (CPU) the system contains.

Declaration:

const

  Test8086: DWord = 2;

Remarks:

Test8086 always is 2 (Intel 80386 or higher). Use CPU_getProcessorType function to get exact processor type (see The ZenTimer Unit for more info).


Test8087 variable

System Unit

Identifies the type of 80x87 processor (FPU) the system contains.

Declaration:

const

  Test8087: DWord = 3;

Remarks:

Test8087 is 3 for 387 or later or 0 if FPU is not detected.


System Unit Procedures and Functions

Abs

Addr

Append

ArcTan

Assign

Assigned

BlockRead

BlockWrite

Break

ChDir

Chr

Close

CompareMem

Concat

Continue

Copy

Cos

Dec

Delete

Dispose

Eof

Eoln

Erase

Exit

Exclude

Exp

FilePos

FileSize

FillChar

Flush

Frac

FreeMem

GetDir

GetMem

Halt

Hi

High

Inc

Include

Insert

Int

IOResult

Length

Ln

Lo

LoCase

Low

MaxAvail

MemAvail

MkDir

Move

New

Odd

Ofs

Ord

ParamCount

ParamStr

Pi

Pos

Pred

Ptr

QSort

Random

Randomize

Read

ReadLn

Rename

Reset

ReWrite

RmDir

Round

RunError

Seek

SeekEof

SeekEoln

SetString

SetTextBuf

Sin

SizeOf

Sqr

Sqrt

Str

Succ

Swap

SwapArgs

Trunc

Truncate

UpCase

Val

Write

WriteLn


Abs function

System Unit

Returns the absolute value of the argument.

Declaration

function Abs(X);

Remarks:

Use Abs to determine the absolute value of an integer or real type argument.

Example:

Var

  x : Integer;

  r : Single;

Begin

  x := Abs(-50);    // 50

  r := Abs(-60.34); // 60.34

End.


Addr function

System Unit

Returns the address of a specified object.

Declaration:

function Addr(X): Pointer;

Remarks:

Use Addr to determine the address of an object. Using Addr is the same as using the @ operator.

Example:

Var

  b : Byte;

  p : Pointer

Begin

  p := Addr(b);  // Same as p := @b;

End.


Append procedure

System Unit

Opens an existing file for appending.

Declaration:

procedure Append(var F:Text);

Append works only if the file exists. It sets the file pointer to the end of the file. If F is open when Append is called then F is first closed and then reopened. If one assigns an empty file name to F, output will be directed to the standard output file. Errors are returned through IOResult if {$I-} If there are no errors then IOResult returns zero.

Example:

var

  Fi:Text;

begin

  Assign(Fi, 'THE_FILE.TXT');

  Append(Fi);

  WriteLn(Fi,'Just testing Append.');

  Close(Fi);

end.


ArcTan function

System Unit

Returns the arctangent of the argument.

Declaration:

function ArcTan(X: Real): Real;

Remarks:

System unit does not provide a Tan function, but tangents can be calculated with the expression: Sin(x) / Cos(x)


Assign procedure

System Unit

Assigns the name of an external file to a file variable.

Declaration:

procedure Assign(var F; FileName; String);

Remarks:

After a call to Assign, all file operations on F are associated with FileName. may consist of a drive and directory specification. If no drive or directory is specified then the current directory is used. If FileName is empty then the standard output defined by operation system is used. Assign should not be used on an open file.

Example:

var

  FiText: Text;

begin

  Assign(FiText, 'TEXTFILE.TXT');

  Rewrite(FiText);

  WriteLn(FiText, 'TextFile is now written to!');

  Close(FiText);

end.


Assigned function

System Unit

Tests to determine if a pointer or procedural variable is nil.

Declaration:

function Assigned(var P): Boolean;

P must be a variable reference of a pointer or procedural type. Assigned(P) corresponds to the test P<> nil for a pointer variable, and @P <> nil for a procedural variable. Returns True if P is nil, False otherwise.


BlockRead procedure

System Unit

Reads one or more records into a variable.

Declaration:

procedure BlockRead(var F: File; var Buf; Count: Longint [; var Result: Longint]);

where:

 F        untyped file variable

 Buf      any variable

 Count    an expression of type Word

 Result   a variable of type Word

Remarks:

BlockRead works only on open files and advances the current file pointer. IOResult returns an error code if an error occurred, otherwise IOResult is set to zero. Also note that BlockRead is not limited to 65,535 (64K) bytes while reading from a file, i.e. Count may be >> 64K.


BlockWrite procedure

System Unit

Writes one or more records from a variable.

Declaration:

procedure BlockWrite(var F: File; var Buf; Count: Longint [; var Result: Longint]);

where:

 F        untyped file variable

 Buf      any variable

 Count    an expression of type Word

 Result   a variable of type Word

Remarks:

BlockWrite works only on open files and advances the current file pointer. IOResult returns an error code if an error occurred, otherwise IOResult is set to zero. Also note that BlockWrite is not limited to 65,535 (64K) bytes while reading from a file, i.e. Count may be >> 64K.


Break procedure

System Unit

Terminates a for, while, or repeat statement.

Declaration:

procedure Break

Remarks:

Causes the innermost enclosing for, while, or repeat statement to be exited immediately.

Is similar to a Goto statement addressing a label just after the end of the innermost enclosing repetitive statement.


ChDir procedure

System Unit

Changes the current directory.

Declaration:

procedure ChDir(S: String);

Remarks:

With {$I-}, IOResult returns an error code if an error occurred, otherwise IOResult is set to zero. The current directory is changed to the path specified by S. If S specifies a drive letter, the current drive is also changed.

Example:

begin

{$I- }

  ChDir('MyDir');

{$I+ }

  if IOResult <> 0 then

    WriteLn('Directory does not exist');

end.


Chr function

System Unit

Returns a character with a specified ordinal number.

Declaration:

function Chr(X: Byte): Char;

Remarks:

Use Chr to generate a character by specifying an integer type number.


Close procedure

System Unit

Closes an open file.

Declaration:

procedure Close(var F);

Remarks:

F is a file variable of any file type previously opened with Reset, ReWrite or Append. The external file associated with F is completely updated and then closed, freeing its file handle for reuse.

With {$I-}, IOResult returns zero if the operation was successful; otherwise, it returns a nonzero error code.

Example:

var

  Fi: Text;

begin

  Assign(Fi, 'C:\DATAFILE.DOC');

  ReWrite(Fi);

  WriteLn(Fi, 'A New File.');

  Close(Fi);  // Close and flush buffer to disk

end.


CompareMem function

Targets: MS-DOS, OS/2, Win32

System Unit

Performs a binary comparison of two memory blocks.

Declaration:

function CompareMem(p1, p2: Pointer; Length: Longint): Boolean;

Remarks:

The CompareMem function returns TRUE if the memory referenced by p1 is identical to that of p2.


Concat function

System Unit

Concatenates a sequence of strings.

Declaration:

function Concat(s1 [, s2,..., sn]: String): String;

Remarks:

The ConCat function concatenates up to 255 characters. Additional characters are ignored. For instance, the following statements return the same results:

s:= ConCat('1234','567890');  // '1234567890'

s:= '1234' + '567890';        // '1234567890'


Continue procedure

System Unit

Continues a for, while, or repeat statement.

Declaration:

procedure Continue;

Remarks:

Causes the innermost enclosing for, while, or repeat statement to immediately proceed with the next iteration.

The compiler will report an error if a call to Continue is not enclosed by a for, while, or repeat statement.


Copy function

Targets: MS-DOS, OS/2, Win32

System Unit

Returns a substring of a string.

Declaration:

function Copy(Str: String; StartPos, Count: Longint):String;

Remarks:

If StartPos is greater than the length of Str than an empty string is returned.

Example:

S := Copy('Hello World',7,5);           // 'World'

S := Copy('Use Protected Mode!',45,10); // ''


Cos function

System Unit

Returns the cosine of the argument (X is an angle, in radians).

Declaration:

function Cos(X: Real): Real;


Dec procedure

System Unit

Decrements an ordinal type variable either by one or by a specified value.

Declaration:

procedure Dec(Var X [; Value:Longint]);

Remarks:

Dec(Int,2);  // Int  := Int - 2;

Dec(Long);   // Long := Long - 1;


Delete procedure

System Unit

Deletes a substring from a string.

Declaration:

procedure Delete(var S: String; Index, Count: Longint);

Remarks:

S is a string-type variable. Index and Count are integer-type expressions. Delete deletes Count characters from S starting at the Index position. If Index is larger than the length of S, no characters are deleted. If Count specifies more characters than remain starting after the Indexth position, the remainder of the string is deleted.

Example:

Delete('AAABBBCCC',4,3);  // 'AAACCC'

Delete('123456789',22,5); // '123456789'


Dispose procedure

System Unit

Disposes of a dynamic variable.

Declaration:

procedure Dispose(var P: Pointer [ , Destructor ]);

Remarks:

P points to a typed variable that was previously assigned either by calling New or by an assignment. Dispose returns the allocated memory, pointed to by P, back to heap . If P does not reference heap, a run time error occurs. References to P^ after a call to Dispose results in undefined data.

Note that dynamic variables are not limited to 65,535 (64K) bytes. For more information about heap, refer to the Heap Management chapter.

Example:

Type

  StrAry  = Array[0..$200] of Char;

var

  StrPtr  : ^StrAry;

begin

  New(StrPtr);

  if StrPtr = nil then

  Halt(1);

  FillChar(StrPtr,$200,'0');

  Dispose(StrPtr);  // Release back to Heap

end.


Eof function

System Unit

Returns the end-of-file status.

Declaration:

function Eof(var F): Boolean;          // for Typed or untyped files

function Eof[(var F: Text)]: Boolean;  // for Text files

Remarks:

If an error occurred, IOResult returns an error code, otherwise IOResult is set to zero.


Eoln function

System Unit

Returns the end-of-line status of a text file.

Declaration:

function Eoln[(var F: Text) ]: Boolean;

Remarks:

If an error occurred, IOResult returns an error code, otherwise IOResult is set to zero.


Erase procedure

System Unit

Erases an external file.

Declaration:

procedure Erase(var F);

Remarks:

Erase must not be used on an open file. IOResult returns zero if Erase was successful, otherwise IOResult contains an error number.


Exit procedure

System Unit

Exits immediately from the current block.

Declaration:

procedure Exit;

While in a procedure or function, Exit causes the subroutine to return to the parent routine. Exit terminates the program if called while in the main routine.

Example:

uses Crt;

procedure ChgColor(ForeGround,BackGround:Byte);

begin

  if not IsColor then Exit;

  SetColor(ForeGround);

  TextBackGround(BackGround);

end;

begin

  ChgColor(Green, Black);

  WriteLn(‘Hellow Green World!’);

end.


Exclude procedure

System Unit

Excludes an element in a set.

Declaration:

procedure Exclude(var S: set of T;I:T);

Remarks:

S is a set type variable, and I is an expression of a type compatible with the base type of S. The element given by I is excluded in the set given by S.


Exp function

System Unit

Returns the exponential of the argument.

Declaration:

function Exp(X: Real): Real;

Remarks:

Exp raises the value e to the power of X, where e is the base of the natural logarithm.


FilePos function

System Unit

Returns the current file position of a file.

Declaration:

function FilePos(var F): Longint;

Remarks:

FilePos returns zero if the file pointer is at the top of the file and returns the file size if at the end of the file. FilePos works only on open files. If an error occurs, IOResult contains the error code, otherwise it is set to zero.


FileSize function

System Unit

Returns the current size of a file.

Declaration:

function FileSize(var F): Longint;

Remarks:

FileSize returns zero if the file is empty, otherwise it returns the number of components in the file. FileSize works only on open files. If an error occurs, IOResult contains the error code, otherwise it is set to zero.


FillChar procedure

System Unit

Fills a specified number (Count) of contiguous bytes with a specified value (can be type Byte or Char).

Declaration:

procedure FillChar(var X; Count: Longint; Ch: Char);

Remarks:

FillChar does not perform range checking and stores Ch as contiguous bytes starting from X for Count length. If used on strings types, set the length byte after calling FillChar.

Note that Count is not limited to 65,535 (64K) bytes.


Flush procedure

System Unit

Flushes the buffer of a text file open for output.

Declaration:

procedure Flush(var F: Text);

Remarks:

Flush only works on files opened for output. Use ReWrite or Append to open a file for output. IOResult contains an error code if an error occurred, otherwise it is set to zero.

Calling Close flushes buffers to disk before closing the file.


Frac function

System Unit

Returns the fractional part of the argument.

Declaration:

function Frac(X: Real): Real;

Remarks:

Frac simply subtracts the integer part of X from X. Frac(X) = X - Int(X).


FreeMem procedure

System Unit

Disposes of a dynamic variable of a given size.

Declaration:

procedure FreeMem(var P: Pointer; Size: Longint);

Remarks:

P points to any type variable that was previously assigned either by calling GetMem or by an assignment. FreeMem returns the allocated memory, pointed to by P, back to heap. Size must match the size of the variable that was allocated by GetMem. If P does not reference heap, a run time error occurs.

The Boolean variable HeapCheck determines whether TMT Pascal tracks the size of dynamic variables. When True, an error occurs if FreeMem is called to deallocate a variable with the

wrong size. This is particularly useful while debugging. References to P^ after a call to FreeMem result in undefined data. For more information about heap, refer to the Heap


GetDir procedure

System Unit

Returns the current directory of a specified drive.

Declaration:

procedure GetDir(D: Byte; var S: String);

where D is set to:

 0     Default

 1     Drive A

 2     Drive B

 3     Drive C

Remarks:

IOResult returns the error code if an error occurred, otherwise it is set to zero.

GetCurDir performs the same function as GetDir but it takes a null-terminated string as an argument instead of a Pascal-style string.


GetMem procedure

System Unit

Creates a dynamic variable of the specified size and puts the address of the block in a pointer variable.

Declaration:

procedure GetMem(var P: Pointer; Size: Longint);

Remarks:

To reference the new variable, use P^. If GetMem finds that there is an insufficient amount of free heap, a runtime error is generated. The boolean variable HeapCheck determines whether TMT Pascal tracks the size of heap variables. This size is for debugging purposes only and is stored in the four bytes before the start of the variable. For more information about heap allocation see the Heap Management chapter.

Example:

uses Crt;

var

  ScrnImage : Pointer;

  Size      : Longint;

begin

  Size := SaveScreenSize(10, 10, 20, 20);

  GetMem(ScrnImage, Size);

  if ScrnImage = nil then

    Halt(1);

  SaveScreen(10,1 0, 20, 20, ScrnImage^);

  ClrScr;

  ...

end.


Halt procedure

System Unit

Stops program execution and returns to the operating system.

Declaration:

procedure Halt [ ( Exitcode: Word ) ];

where:

 Exitcode is an optional expression that specifies the exit code of your  program.

Remarks:

The exit code can be retrieved in DOS by using ErrorLevel in a batch file. If the program does not return to DOS, use DosExitCode to determine the exit code. For more information about ErrorLevel consult your DOS reference manual.

Example:

begin

  if ParamCount <> 1 then

  begin

    WriteLn('Error: No parameters passed.');

    Halt(1);

  end;

  ...

end.


Hi function

System Unit

Returns the high-order byte of the argument.

Declaration:

function Hi(X): Byte;

Remarks:

Use Hi to retrieve the high order byte from an ordinal type argument.


High function

System Unit

Returns the highest value in the range of the argument.

Declaration:

function High(X)


Inc procedure

System Unit

Increments a variable.

Declaration:

procedure Inc(var X [ ; N: Longint ] );

Remarks:

If N is not passed to Inc, X is incremented by one. Otherwise, Inc is identical to X := X + n. Inc produces more efficient code.

Example:

Inc(Int,7); // Int  := Int + 7

Inc(Long);  // Long := Long + 1


Include procedure

System Unit

Includes an element in a set.

Declaration:

procedure Include(var S: set of T; I:T);

Remarks:

S is a set type variable, and I is an expression of a type compatible with the base type of S. The element given by I is included in the set given by S.

The construct Include (S,I) corresponds to S := S + (I) but the Include procedure generates more efficient code.


Insert procedure

System Unit

Inserts a substring into a string.

Declaration:

procedure Insert(Src: string; var Dst: string; Pos: Longint);

Remarks:

Src is a string-type expression. Dst is a string-type variable. Pos is an integer expression. Insert inserts Src into Dst at the Posth position. If the resulting string is longer than 255 characters, it is truncated after the 255th character.


Int function

System Unit

Returns the Integer part of the argument.

Declaration:

function Int(X: Real): Real;

Remarks:

Int returns the integer portion of a real number rounded toward zero.

Example:

i := Int(-456.332);   // -456

i := Int(1231.98192); // 1231


IOResult function

System Unit

Returns the status of the last I/O operation performed. Return zero (0) if successful.

Declaration:

function IOResult: Integer;

Remarks:

I/O-checking must be off {$I-} to trap I/O errors using IOResult. If an I/O error occurs and I/O-checking is off, all subsequent I/O operations are ignored until a call is made to IOResult. A call to IOResult clears the internal error flag. A call to IOResult clears its internal error flag. I/O-checking must be off {$I-}.


Length function

System Unit

Returns the dynamic length of a string.

Declaration:

function Length(S: String): Integer;


Ln function

System Unit

Returns the natural logarithm of the argument.

Declaration:

function Ln(X: Real): Real;


Lo function

System Unit

Returns the low-order Byte of the argument.

Declaration:

function Lo(X): Byte;


LoCase function

System Unit

Converts a character to lowercase.

Declaration:

function LoCase(Ch: Char): Char;

Remarks:

Ch is of char type.

LoCase simply returns an lowercase character if Ch is uppercase.


Low function

System Unit

Returns the lowest value in the range of the argument.

Declaration:

function Low(X);

Remarks:

Result type is X, or the index type of X where X is either a type identifier or a variable reference.


MaxAvail function

System Unit

Returns the lowest value in the range of the argument.

Returns the size of the largest contiguous free block in the heap.

Declaration:

function MaxAvail: Longint;


MemAvail function

System Unit

Returns the amount of all free memory in the heap.

Declaration:

function MemAvail: Longint;


MkDir procedure

System Unit

Creates a subdirectory with given name.

Declaration:

procedure MkDir(S: String);


Move procedure

System Unit

Copies bytes from source to dest.

Declaration:

procedure Move(var Source, Dest; Count: Longint);

Remarks:

Copies a specified number of contiguous bytes (Count) from a source range to a destination  range. No range-checking is performed. Whenever possible, use SizeOf to determine the count.

Note that Count is not limited to 65,535 (64K) bytes.


New procedure

System Unit

Creates a new dynamic variable and sets a pointer variable to point to it.

Declaration:

procedure New(Var P: Pointer);

Remarks:

New determines the amount of heap to allocate by the size of the typed variable pointed to by P. To reference the new variable, use P^. If New finds that there is an insufficient amount of free heap, a runtime error  is generated.

The Boolean variable HeapCheck determines whether TMT Pascal tracks the size of heap variables. This size is for debugging purposes only and is stored in the four bytes before the start of the variable. For more information about heap allocation see the Heap Management chapter. Note that the size of heap variables is not limited to 66,535 (64K) bytes.

Example:

var

  P: ^String[16];

begin

  New(P);

  P^ := 'How are you?';

  Writeln(P^);

  Dispose(P);

end.


Odd function

System Unit

Tests if the argument is an odd number.

Declaration:

function Odd(X: Longint): Boolean;


Ofs function

System Unit

Returns the linear offset in memory of a specified object.

Declaration:

function Ofs(X): DWord;


Ord function

System Unit

Returns the ordinal value of an ordinal-type expression.

Declaration:

function Ord(X): Longint;


ParamCount function

System Unit

Returns the number of parameters passed to the program on the command line.

Declaration:

function ParamCount: Word;

Remarks:

Command line parameters are separated by spaces or tabs. To retrieve command line parameters call ParamStr.

Example:

begin

  if ParamCount = 0 then

  begin

    WriteLn('No parameters specified.');

    Halt(1);

  end;

end.


ParamStr function

System Unit

Returns a specified command-line parameter.

Declaration:

function ParamStr(Index: Word): String;

Remarks:

If Index is zero then the path and file name of the current program is returned. Command line parameters are separated by spaces or tabs. To determine the number of command line parameters use ParamCount.

Example:

var

  Cnt: Longint;

begin

  WriteLn('Program Name: ',ParamStr(0));

  if ParamCount = 0 then

     Halt(0);

  for Cnt := 1 to ParamCount do

   WriteLn(ParamStr(Cnt));

end.


Pi function

System Unit

Returns the value of Pi, which is defined as 3.1415926535897932385.

Declaration:

function Pi: Extended;


Pos function

System Unit

Searches for a substring in a string.

Declaration:

function Pos(SubStr: String; S: String): Byte;

Remarks:

Pos returns the index of the first character of SubStr in S. If SubStr is not found then Pos returns zero.

Example:

Index := Pos('23','123'); // Index is 2

Index := Pos('z','ABC');  // Index is 0


Pred function

System Unit

Returns the predecessor of the argument.

Declaration:

function Pred(X);

Remarks:

X is an ordinal-type expression. The result, of the same type as X, is the predecessor of X.

Example:

n := Pred(500);  // n is 499


Ptr function

System Unit

Converts an offset address to a pointer-type value.

Declaration:

function Ptr(Ofs: DWord): Pointer;


QSort procedure

Targets: MS-DOS, OS/2, Win32

System Unit

Performs a quick sort.

Declaration:

procedure QSort(base: Pointer; num, width: Integer; function CompFunc conv arg_based (const elem1, elem2: Pointer): Boolean);

Remarks:

The QSort procedure implements a quick-sort algorithm to sort an array of num elements, each of width bytes. The argument base is a pointer to the base of the array to be sorted. QSort replaces this array with the sorted elements. The argument CompFunc is a user-supplied function that compares two array elements and returns a value specifying their relationship. QSort calls the CompFunc function one or more times during the sort, passing pointers to two array elements on each call. The routine must compare the elements, then return one of the following values:

Return Value   Description

< 0	elem1 less than elem2

0	elem1 equivalent to elem2

> 0	elem1 greater than elem2

Example:

// This program uses qsort to sort

// an array of Integers in ascending order.

{$ifdef __GUI__}

uses WinCRT;

{$endif}

function CompFunc conv arg_based (const elem1, elem2: Pointer): Boolean;

begin

  Result := Integer(elem1^) > Integer(elem2^);

end;

procedure PrintArray(hdr: String; arg: array(1) of Integer);

var

  i: Integer;

begin

  Write(hdr);

  for i := 0 to high(arg)[0] do

     Write(arg[i], ' ');

  Writeln;

end;

var

  a: array[0..9] of Integer;

  i: Integer;

begin

  for i := 0 to 9 do

    a[i] := Random(100) - Random(100);

  PrintArray('Initial: ', a);

  QSort(@a, 10, SizeOf(Integer), CompFunc);

  PrintArray(' Sorted: ', a);

end.


Random function

System Unit

Returns a random number.

Declaration:

function Random [ ( Range: Word) ];

Remarks:

Range, if specified, results in 0 <= Result < Range. If not specified, the range is 0 <= Result < 1.

A call to Randomize should be made prior to Random. This initializes the random number generator.

Example:

begin

  Randomize;

  repeat

    Writeln(Random(65535));

  until KeyPressed;

end.


Randomize procedure

System Unit

Initializes the built-in random number generator with a random value (obtained from the system clock).

Declaration:

procedure Randomize;

Example:

begin

  Randomize;

  repeat

    Writeln(Random(65535));

  until KeyPressed;

end.


Read procedure

System Unit

Read from a file into one or more variables.

Declaration:

procedure Read(F, var V1[, V2,...,Vn ] );          // For typed files

procedure Read([var F: Text; ] V1[, V2,...,Vn ]);  // For text files

Remarks:

Depending on the type of the variable or variables passed, Read copies the contents of the file, from the current file pointer, into the variable and advances the pointer. If Read cannot match the type of the variable with the contents of the file, an I/O error occurs. End of line (#13) as well as end of file (#26) cause Read to terminate.

For integers, Read expects an integer number in string form. Tabs, blank spaces, or end of line markers before the number are all skipped. When encountered thereafter, Read terminates.

For real variables, Read expects a number in real format. Blanks, tabs or end of line markers preceding the real string are skipped. When encountered thereafter, Read stops.

With strings, Read reads up to either an end of line marker or an end of file marker. If the string read is longer than 255 characters, it is truncated. Read does not advance the file.


ReadLn procedure

System Unit

Executes the Read procedure then skips to the next line of the file.

Declaration:

procedure ReadLn([ var F: Text; ] V1 [, V2, ...,Vn ]);

Remarks:

Depending on the type of the variable or variables passed, ReadLn copies the contents of the file, from the current file pointer, into the variable and advances the pointer. If ReadLn cannot match the type of the variable with the contents of the file, an I/O error occurs. End of line (#13) as well as end of file (#26) cause ReadLn to terminate.

The file must be a text file or standard input. ReadLn is identical to Read except that it advances passed the end of line marker.

With {$I-}, IOResult returns an error code if the operation was not successful. If no error was encountered, IOResult is set to zero.

Example:

var

  Name: String;

  Age:  DWord;

begin

  Write('Enter your name: ');

  ReadLn(Name);

  Write('Enter your age : ');

  ReadLn(Age);

  if Age < 21 then

    WriteLn('You’re so young, ', Name, '!')

  else if Age < 40 then

    WriteLn(Name, ', you`re still in your prime!')

  else if Age < 60 then

    WriteLn('You`re over the hill, ', Name, '!')

  else if Age < 80 then

    WriteLn('I bow to your wisdom, ', Name, '!')

  else

    Writeln('Are you really ', Age, ', ', Name, '?');

end.


Rename procedure

System Unit

Renames an external file.

Declaration:

procedure Rename(var F; NewName);

Remarks:

Rename must not be used on an open file. All operations after a successful call to Rename use the new name. With {$I-}, IOResult returns zero if Rename was successful, otherwise IOResult contains an error number.


Reset procedure

System Unit

Opens an existing file.

Declaration:

procedure Reset(var F [: File; RecSize: Longint ] );

Remarks:

F is a file variable of any type which was previously associated with a file name by a call to Assign. The external file must exist.

RecSize indicates the size in bytes of each record and can only be passed if F is an untyped file. Note that RecSize is not limited to 65,535 (64K) bytes.

If F is open when Reset is called, F is first closed and then reopened. If F is assigned to an empty string (‘’) then standard input is used. Text files are opened as read-only. A record size of 128 bytes is assumed if F is not a text file and RecSize is not passed.

Reset sets the file pointer to the top of the file. With {$I-}, IOResult returns an error code if an error occurred, otherwise it is set to zero.


ReWrite procedure

System Unit

Creates and opens a new file.

Declaration:

procedure ReWrite(var F: File [; RecSize: Longint ] );

Remarks:

F is a file variable of any type which was previously associated with a file name by a call to Assign.

RecSize indicates the size in bytes of each record and can only be passed if F is an untyped file. Note that RecSize is not limited to 65,535 (64K) bytes.

If F exists or is open when ReWrite is called, F is closed, deleted, and then recreated. If F is assigned to an empty string (‘’), standard input is used. Text files are created as write-only. A record size of 128 bytes is assumed if F is not a text file and RecSize is not passed. With {$I-}, IOResult returns an error code if an error occurred, otherwise it is set to zero.


RmDir procedure

System Unit

Removes an empty subdirectory.

Declaration:

procedure RmDir(Dir: String);

Remarks:

IOResult returns an error code if Dir is an empty string, if Dir does not exist, or if Dir is not an empty directory. Otherwise, IOResult is set to zero.


Round function

System Unit

Rounds a Real-type value to an Integer-type value.

 Declaration:

function Round(X: Real): Longint;

Remarks:

Round returns X, rounded to the nearest whole number, as a longint.

Example:

i := Round(-456.332);    // -456

i := Round(1231.98192);  // 1232


RunError procedure

System Unit

Stops program execution.

Declaration:

procedure RunError [ ( ExitCode: Word ) ];

Remarks:

ExitCode, if specified, is the runtime error number. If not passed, the exit code is zero.

RunError is used for debugging purposes. It generates an error during execution along with an offset. This procedure is similar to Halt.


Seek procedure

System Unit

Moves the current position of a file to a specified component.

Declaration:

procedure Seek(var F; NewPos: Longint);

Remarks:

F is a file of any type except text.

NewPos is the record or component to move the file pointer to.

Seek works only on open files and cannot be used with text files. The first component of any file is zero. With {$I-} IOResult returns an error code if an error occurred, otherwise it is set to zero.


SeekEof procedure

System Unit

Returns the end-of-file status of a file.

Declaration:

function SeekEof [ (var F: Text) ]: Boolean;

Remarks:

SeekEof works only on text files and is similar to Eof however it ignores blanks, tabs, and end of line markers that may exist before the end of file marker. With {$I-}, IOResult returns an error code if an error occurred, otherwise it is set to zero.


SeekEoln procedure

System Unit

Returns the end-of-line status of a file.

Declaration:

function SeekEoln [ (var F: Text) ]: Boolean;

Remarks:

Must be used on text files. File (F) must be open.


SetString procedure

System Unit

Sets the contents and length of the given string.

Declaration:

procedure SetString(var S: string; Buffer: PChar; Len: DWORD);

Remarks:

The SetString sets the length indicator character (the character at S[0]) to the value given by Len and then, if the Buffer parameter is not nil, copies Len characters from Buffer into the string starting at S[1]. For a short string variable, the Len parameter must be a value between 0 and 255.


SetTextBuf procedure

System Unit

Assigns an I/O buffer to a text file.

Declaration:

procedure SetTextBuf(var F: Text; var Buf [ ; Size: LongInt ] );

Remarks:

F is a text file that has not yet been opened. Buffer is a variable of any type. Size, if specified, is the size of the new buffer. Otherwise SizeOf(Buffer) is assumed.

Note that the new buffer's size is not limited to 65,535 (64K) bytes.

By default each text file has a 128 byte buffer that is used for I/O. SetTextBuf assigns a new buffer to the text file. By creating a larger buffer I/O operations become faster because there are fewer disk reads and writes.


Sin function

System Unit

Returns the sine of the argument.

Declaration:

function Sin(X: Real): Real;


SizeOf function

System Unit

Returns the number of bytes occupied by the argument.

Declaration:

function SizeOf(X): Longint;

Remarks:

X is a variable reference or type identifier. SizeOf returns the number of bytes used by the argument.


Sqr function

System Unit

Returns the square of the argument.

Declaration:

function Sqr(X);

Remarks:

X is either an integer type or real type. Sqr returns (X * X).


Sqrt function

System Unit

Returns the square root of the argument.

Declaration:

function Sqrt(X: Real): Real;

Remarks:

X is either single, double, or extended.


Str procedure

System Unit

Converts a numeric value to a string.

Declaration:

procedure Str(X [: Width [: Decimals ]]; var S:string);

Remarks:

X is either a real or integer type. Width, if specified, is the number of characters to reserve for the integer portion of the number. Decimals, if specified, is the number of character to reserve for the decimal portion of a real type number.

S returns the result of the operation. Str formats numbers exactly like Write does when printing integers or real types.


Succ function

System Unit

Returns the successor of the argument.

Declaration:

function Succ(X);

Remarks:

X is an expression of ordinal type.

Example:

n := Succ(4);   // n = 5

c := Succ('a'); // c = 'b'


Swap function

System Unit

Swaps the high- and low-order bytes of the argument.

Declaration:

function Swap(X: Integer): Integer;

function Swap(X: Longint): Longint;

Example:

n := Swap($1234);  // n = $3412


SwapArgs procedure

Targets: MS-DOS, OS/2, Win32

System Unit

Swaps its arguments.

Declaration:

procedure SwapArgs(var A, B: Char);

procedure SwapArgs(var A, B: Byte);

procedure SwapArgs(var A, B: Word);

procedure SwapArgs(var A, B: DWORD);

procedure SwapArgs(var A, B: SmallInt);

procedure SwapArgs(var A, B: Longint);

procedure SwapArgs(var A, B: Int64);

procedure SwapArgs(var A, B: Real48);

procedure SwapArgs(var A, B: Single);

procedure SwapArgs(var A, B: Double);

procedure SwapArgs(var A, B: Extended);

procedure SwapArgs(var A, B: Pointer);

procedure SwapArgs(var A, B: String);


Trunc function

System Unit

Truncates a real-type value to an Integer-type value.

Declaration:

function Trunc(X: Real): Longint;

Remarks:

X is either single, double, or extended. Trunc returns X, rounded towards zero, as a Longint.


Truncate procedure

System Unit

Truncates the file at the current file position.

Declaration:

procedure Truncate(var F);

Remarks:

F is any type file except text.

Truncate deletes all data passed the current file pointer of F. An end of file marker, Ctrl-Z, is inserted at the current file pointer. With {$I-} IOResult returns an error code if the operation failed. Otherwise IOResult is set to zero.


UpCase function

System Unit

Converts a character to uppercase.

Declaration:

function UpCase(Ch: Char): Char;

Remarks:

Ch is of char type.

UpCase simply returns an uppercase character if Ch is lowercase.


Val procedure

System Unit

Converts a string value to its numeric representation.

Declaration:

procedure Val(S; var Value; var Code: Integer);

Remarks:

S is of string type. Value is an integer or real type variable. Code returns an integer value indicating whether the operation was successful or where it failed.

S is a string of numeric characters. Val attempts to convert S to a valid integer or real types number. If successful, Code returns zero, otherwise Code returns the index in S where the conversion failed.

Example:

uses Strings;

var

  Num: String;

  Code: Longint;

  Value: Extended;

begin

  Write('Enter a number: ');

  ReadLn(Num);

  Val(Num, Value, Code);

  if Code <> 0 then

    Writeln('Error at position: ', Code)

  else

    Writeln('(Value * 2) = ', Fls(Value * 2));

end.


Write procedure

System Unit

For typed files, writes a variable into a file component. For text files,  writes one or more values to the file

Declaration:

procedure Write( [ var F: Text; ] P1 [,P2,...,Pn ];

Remarks:

F, if specified, is a file variable. If omitted Output is assumed.

P1 may be of char, string, integer, real, or Boolean type. P1 through Pn are output to F. Each P parameter may be formatted as follows:

P [:MinWidth [:Decimals] ]

where P is the value to output. MinWidth, which must be greater than zero, specifies the minimum width of P. Decimals specifies the number of decimal places to be output when P is of real type.

Example:

begin

  Write('A wonderful string!');

  Write(500);

  Write(5.5:5:2)

  Write(True);

end.


WriteLn procedure

System Unit

Executes the Write procedure, then outputs an end-of-line marker to the file.

Declaration:

procedure Writeln([ var F: Text; ] P1 [, P2, ...,Pn ] );

Remarks:

F, if specified, is a file variable. If omitted Output is assumed. P1 may be of char, string, integer, real, or Boolean type. P1 through Pn are output to F. Each P parameter may be formatted as follows:

P [:MinWidth [:Decimals]]

where P is the value to output. MinWidth, which must be greater than zero, specifies the minimum width of P. Decimals specifies the number of decimal places to be output when P is of real type.

The file used by WriteLn must be open for output. An end of line marker is written to F after output.

Example:

var

  Name: String;

  Age:  DWord;

begin

  Write('Enter your name: ');

  ReadLn(Name);

  Write('Enter your age : ');

  ReadLn(Age);

  if Age < 21 then

    WriteLn('You’re so young, ', Name, '!')

  else if Age < 40 then

    WriteLn(Name, ', you`re still in your prime!')

  else if Age < 60 then

    WriteLn('You`re over the hill, ', Name, '!')

  else if Age < 80 then

    WriteLn('I bow to your wisdom, ', Name, '!')

  else

    Writeln('Are you really ', Age, ', ', Name, '?');

end.


The Use16 Unit

Targets: MS-DOS, OS/2, Win32

Contains redefinition of integer types for 16-bit computing as follows:

type

  Integer  = System.SmallInt;

  PInteger = ^System.SmallInt;

const

  MAXINT      = High(System.SmallInt);

  MAXINTEGER  = High(System.SmallInt);

  MININT      = Low(System.SmallInt);

  MININTEGER  = Low(System.SmallInt);


The Use32 Unit

Targets: MS-DOS, OS/2, Win32

Contains redefinition of integer types for 32-bit computing as follows:

type

  Word       = System.DWORD;

  PWord      = ^System.DWORD;

const

  MAXWORD    = High(System.DWORD);

  MINWORD    = Low(System.DWORD);


The WinDos Unit

The WinDos unit allows easy access to most of the functions provided by the MS-DOS operating system from 32-bit protected mode application. Operations such as find file, disk size or status, time and date, get environment strings, and more are provided by the WinDos unit. It provides a PChar interface to the file handling functions.

WinDos Unit Constants and Variables

WinDos Unit Procedures and Functions


WinDos Unit Constants and Variables

Flag constants

File-mode constants

File-attribute constants

TDataTime type

DosError variable

TRegisters type

TSearchRec type


TDataTime type

WinDos Unit

The UnpackTime and PackTime procedures use variables of type DateTime to examine and construct 4-byte, packed date-and-time values for the GetFTime, SetFTime, FindFirst, and FindNext procedures:

Declaration:

type

  TDateTime = record

    Year, Month, Day, Hour,

    Min, Sec: Word;

  end;


TRegisters type

WinDos Unit

The Intr and MsDos procedures use variables of type Registers to specify the input register contents and examine the output register contents of a software interrupt.

Declaration:

type TRegisters =

  record

  case Integer of

    1: (edi, esi, ebp, _res, ebx, edx, ecx, eax: Longint;

        flags, es, ds, fs, gs, ip, cs, sp, ss: Word);

    2: (_dmy2: array [0..15] of byte; bl, bh, b1, b2, dl,

        dh, d1, d2, cl, ch, c1, c2, al, ah: Byte);

    3: (di, i1, si, i2, bp, i3, i4, i5, bx, b3, dx, d3, cx,

        c3, ax: Word);

  end;


TSearchRec type

WinDos Unit

The FindFirst and FindNext procedures use variables of type SearchRec to scan directories:

Declaration:

MS-DOS target

type

  TSearchRec = record

    Fill : array[1..21] of Byte;

    Attr : Byte;

    Time : Longint;

    Size : Longint;

    Name : string[12];

end;

OS/2 target

type

  TSearchRec = record

    Fill : array[1..21] of Byte;

    Attr : Byte;

    Time : Longint;

    Size : Longint;

    Name : string;

end;

Win32 target

type

  TSearchRec = record

    Fill : array[1..21] of Byte;

    Attr : Byte;

    Time : Longint;

    Size : Longint;

    Name : TFileName;

    ExcludeAttr: Longint;

    FindHandle: THandle;

    FindData: TWin32FindData;

  end;

Information for each file found by FindFirst or FindNext is reported back in a SearchRec.

Field    Meaning

Attr     File's attributes

Time     File's packed date and time

Size     File's size, in bytes

Name     File's name

The Fill field is reserved by DOS and should never be modified.


WinDos Unit Procedures and Functions

CreateDir

DiskFree

DiskSize

DosVersion

FileExpand

FindFirst

FindNext

FileSearch

FileSplit

GetArgCount

GetArgStr

GetCBreak

GetCurDir

GetDate

GetEnvVar

GetFAttr

GetFTime

GetIntVec

GetTime

GetVerify

Intr

MsDos

PackTime

RemoveDir

SetCBreak

SetCurDir

SetDate

SetFAttr

SetFTime

SetIntVec

SetTime

SetVerify

UnpackTime


CreateDir procedure

WinDos Unit

Creates a new subdirectory.

Declaration:

procedure CreateDir(Dir: PChar);

Remarks:

Performs the same functions as MkDir, but uses a null-terminated (PChar) string rather than a Pascal-style string.


FileExpand function

WinDos Unit

Expands a file name into a fully-qualified file name.

Declaration:

function FileExpand(Dest, Name: PChar): PChar;


FileSearch function

WinDos Unit

Searches for a file.

Declaration:

function FileSearch(Dest, Name, List: PChar): PChar;

Remarks:

List is a list of the directories to include in the search each delimited with a semicolon (;).

FileSearch returns the directory and file name if the file has been located. If Path is not found then an empty string is returned. FileSearch always begins with the current directory and then checks the directories listed in List in the order that they appear.

See also:

FindFirst

FileExpand

FileSplit


FileSplit procedure

WinDos Unit

Splits a file name into its three components.

Declaration:

procedure FileSplit(Path, Dir, Name, Ext: PChar): DWORD

Remarks:

Use this procedure to break down a file specification into three parts: path, file name, and file extension. Dir returns the path or directory part of Path. Name returns the actual file name without extension. Ext returns the file extension preceded by a period (.).

It is possible that one or more of the components be returned  empty. This occurs if Path contains no such component. For instance, if there is no path, Dir is empty.


GetArgCount function

WinDos Unit

Returns the number of parameters passed to the program on the command line.

Declaration:

function GetArgCount: Longint;

Remarks:

Command line parameters are separated by spaces or tabs. To retrieve command line parameters call GetArgCount.

Example:

uses WinDos;

begin

  if GetArgCount = 0 then

  begin

    WriteLn('No parameters specified.');

    Halt(1);

  end;

end.


GetArgStr function

WinDos Unit

Returns a specified command-line parameter.

Declaration:

function GetArgStr(Dest: PChar; Index: Longint; MaxLen: DWORD): PChar;


GetCurDir function

WinDos Unit

Returns the current directory of a specified drive.

Declaration:

function GetCurDir(Dir: PChar; Drive: Byte): PChar;

Remarks:

where

   0	Default drive

   1	Drive A

   2	Drive B

   3	Drive C

and so on...


GetEnvVar function

WinDos Unit

Returns the value of a specified environment variable.

Declaration:

function GetEnvVar(var Name: PChar): PChar;

Remarks:

Name is the name of the variable to retrieve. If Name does not exist as an environment variable then an empty string is returned.


RemoveDir procedure

WinDos Unit

Removes an empty subdirectory.

Declaration:

procedure RemoveDir(Dir: PChar);


SetCurDir procedure

WinDos Unit

Changes the current directory to the specified path.

Declaration:

procedure SetCurDir(Dir: PChar);


The ZenTimer Unit

The ZenTimer unit is a full-featured port to TMT Pascal of ZTimer library by SciTech Software and based on original C/C++ code by Kendall Bennett, SciTech Software. The ZenTimer description is based on the MegaGraph Graphics Library Reference Manual Copyright (c) 1996 SciTech Software Inc.

Copyrights:

Copyright (C) 1995-99 TMT Development Corporation.

Portions Copyright (C) 1991-1997 SciTech Software, Inc.

All rights reserved.

Features:

•	High resolution Zen Timer (based on code from book "Zen of Assembly Language" Volume 1, Knowledge by Michael Abrash).

•	Ultra long Zen Timer (interface to the BIOS Timer Tick for timing code that takes up to 24 hours).

•	RDTSC support (uses supports the Intel RDTSC instruction, for high precision timing).

•	Routines to obtain CPU information (type, speed, features, 3DNow!™ and MMX™ support).

•	LZTimer and ULZTimer objects (provide a set of Pascal objects to manipulate the Zen Timers).

ZenTimer Unit Procedures and Functions


ZentTimer Unit Procedures and Functions
ZenTimer Unit Procedures and Functions

CPU_getCPUIdFeatures

CPU_getProcessorSpeed

CPU_getProcessorType

CPU_haveMMX

CPU_have3DNow

LZDelay

LZTimerCount

LZTimerLap

LZTiemerOff

LZTiemerOn

LZTimerResolution

ULZDelay

ULZElapsedTime

ULZReadTime

ULZTimerCount

ULZTimerLap

ULZTimerOff

ULZTimerOn

ULZTimerResolution

ZTimerInit


CPU_getCPUIdFeatures function

ZenTimer Unit

Returns CPUID features (family/model/stepping/features).

Declaration:

function CPU_getCPUIdFeatures: DWord;


CPU_getProcessorSpeed function

ZenTimer Unit

Returns the speed of the processor in Mhz.

Declaration:

function CPU_getProcessorSpeed: DWord;

Remarks:

This function returns the speed of the CPU in Mhz. Note that if the speed cannot be determined, this function will return 0.

Example:

{$ifndef __CON__}

  This program must be compiled for MS-DOS, OS/2 or Win32 console mode

{$endif}

uses ZenTimer;

begin

  Writeln('CPU speed is ', CPU_getProcessorSpeed,' Mhz');

end.


CPU_getProcessorType function

ZenTimer Unit

Returns the type of processor in the system.

Declaration:

function CPU_getProcessorType: DWord;

Remarks:

Returns the type of processor in the system. Note that if the CPU is an unknown Pentium family processor that we don't have an enumeration for, the return value will be greater than or equal to the value of CPU_UnkPentium (depending on the value returned by the CPUID instruction).

Following constants are defined:

const

  CPU_unknown     = 0;   // Unknown proccessor

  CPU_i386        = 1;   // Intel 80386 processor

  CPU_i486        = 2;   // Intel 80486 processor

  CPU_Pentium     = 3;   // Intel Pentium(R) processor

  CPU_PentiumPro  = 4;   // Intel PentiumPro(R) processor

  CPU_PentiumII   = 5;   // Intel PentiumII(R) processor

  CPU_PentiumIII  = 6;   // Intel PentiumIII(R) processor

  CPU_UnkPentium  = 7;   // Unknown Intel Pentium family processor

Also defined CpuTypes array strings.

const

  CpuTypes: array [0..7] of string =

  (

  'Unknown',

  'Intel 80386',

  'Intel 80486',

  'Intel Pentium(R)',

  'Intel PentiumPro(R)',

  'Intel PentiumII(R)',

  'Intel PentiumIII(R)',

  'Unknown Pentium'

  );

Example:

{$ifndef __CON__}

  This program must be compiled for MS-DOS, OS/2 or Win32 console mode

{$endif}

uses ZenTimer;

begin

  Writeln('CPU is ', CpuTypes[CPU_getProcessorType]);

end.


CPU_haveMMX function

ZenTimer Unit

Returns True if the processor supports Intel MMX™ extensions.

Declaration:

function CPU_haveMMX: Boolean;

Remarks:

This function determines if the processor supports the Intel MMX™ extended instruction set. If the processor is not an Intel or Intel clone CPU, this function will always return False.

Example:

{$ifndef __CON__}

  This program must be compiled for MS-DOS, OS/2 or Win32 console mode

{$endif}

uses ZenTimer;

begin

  if CPU_haveMMX then

    Writeln('MMX technology supported')

  else

    Writeln('MMX technology not supported');

end.


CPU_have3DNow function

ZenTimer Unit

Returns True if the processor supports AMD 3DNow!™ extensions.

Declaration:

function CPU_have3DNow: Boolean;

Remarks:

This function determines if the processor supports the AMD 3DNow!™ extended instruction set.

Example:

{$ifndef __CON__}

  This program must be compiled for MS-DOS, OS/2 or Win32 console mode

{$endif}

uses ZenTimer;

begin

  if CPU_have3DNow then

    Writeln('3DNow! technology supported')

  else

    Writeln('3DNow! technology not supported');

end.


LZDelay procedure

ZenTimer Unit

Delays a specified number of 1e-6 sec.

Declaration:

procedure LZDelay (Value: DWord);


LZTimerCount function

ZenTimer Unit

Returns the current count for the Long Period Zen Timer.

Declaration:

function LZTimerCount: Dword;

Remarks:

Returned value is a current count that has elapsed between calls to LZTiemerOn and LZTiemerOff in microseconds.

Example:

program LZTest;

{$ifndef __CON__}

  This program must be compiled for MS-DOS, OS/2 or Win32 console mode

{$endif}

uses ZenTimer;

function lu06(val: Longint): String;

var

  i: Longint;

  s: String;

begin

  Str(val:6,s);

  for i := 1 to 6 do

    if s[i] = ' ' then s[i] := '0';

  lu06 := s;

end;

procedure ReportTime(count: Longint);

var

  secs: Longint;

begin

  secs := count div 1000000;

  count := count - secs * 1000000;

  Writeln('Time taken: ', secs, '.', lu06(count), ' seconds');

end;

var

  i, j: DWord;

begin

  LZTimerOn;

   for j := 0 to 9 do

     for i := 0 to 19999 do

       i := i;  // do something

  LZTimerOff;

  ReportTime(LZTimerCount);

end.


LZTimerLap function

ZenTimer Unit

Returns the current count for the Long Period Zen Timer and keeps it running (count that has elapsed in microseconds).

Declaration:

function LZTimerLap: Dword;

Remarks:

Returned value is a current count that has elapsed since the last call to LZTiemerOn in microseconds. The time continues to run after this function is called so you can call this function repeatedly.


LZTiemerOff procedure

ZenTimer Unit

Stops the Long Period Zen Timer counting.

Declaration:

procedure LZTimerOff;

Remarks:

Stops the Long Period Zen Timer counting and latches the count. Once you have stopped the timer you can read the count with LZTimerCount. If you need highly accurate timing, you should use the on and off functions rather than the lap function since the lap function does not subtract the overhead of the function calls from the timed count.


LZTiemerOn procedure

ZenTimer Unit

Starts the Long Period Zen Timer counting.

Declaration:

procedure LZTimerOn;

Remarks:

Starts the Long Period Zen Timer counting. Once you have started the timer, you can stop it with LZTiemerOff or you can latch the current count with LZTimerLap.

The Long Period Zen Timer uses a number of different high precision timing mechanisms to obtain microsecond accurate timings results whenever possible. The following different techniques are used depending on the runtime

environment and CPU on the target machine. If the target system has a Pentium CPU installed which supports the Read Time Stamp Counter instruction (RDTSC), the Zen Timer library will use this to obtain the maximum timing precision available.

If the Pentium RDTSC instruction is not available, we then do all timing using the old style 8253 timer chip. The 8253 timer routines provide highly accurate timings results in pure DOS mode, however in a DOS box under Windows or other Operating Systems the virtualization of the timer can produce inaccurate results.

Because the Long Period Zen Timer stores the results in a 32-bit unsigned integer, you can only time periods of up to 232 microseconds, or about 1hr 20mins. For timing longer periods use the Ultra Long Period Zen Timer.


LZTimerResolution function

ZenTimer Unit

Returns the resolution of the Ultra Long Period Zen Timer.

Declaration:

function LZTimerResolution: Real;

Remarks:

Returns the resolution of the Long Period Zen Timer as a floating point value measured in seconds per timer count. This function always returns 1e-6.


ULZDelay procedure

ZenTimer Unit

Delays a specified number of 0.054925 sec.

Declaration:

procedure ULZDelay (Value: DWord);


ULZElapsedTime function

ZenTimer Unit

Compute the elapsed time between two timer counts.

Declaration:

function ULZElapsedTime(start, finish: DWord): DWord

Remarks:

Returns the elapsed time for the Ultra Long Period Zen Timer in units of the timers resolution (1/18th of a second under DOS). This function correctly computes the difference even if a midnight boundary has been crossed during the timing period.


ULZReadTime function

ZenTimer Unit

Reads the current time from the Ultra Long Period Zen Timer.

Declaration:

function ULZReadTime: DWord;

Remarks:

Returned value is a current Ultra Long Period Zen Timer and returns its current count. You can use the ULZElapsedTime function to find the elapsed time between two timer count readings.


ULZTimerCount function

ZenTimer Unit

Returns the current count for the Ultra Long Period Zen Timer.

Declaration:

function ULZTimerCount: DWord;

Remarks:

Returned value is a current count that has elapsed between calls to ULZTimerOn and ULZTimerOff in resolution counts.


ULZTimerLap function

ZenTimer Unit

Returns the current count for the Ultra Long Period Zen Timer and keeps it running.

Declaration:

function ULZTimerLap: DWord;

Remarks:

Returned value is a current count that has elapsed since the last call to ULZTimerOn in microseconds. The time continues to run after this function is called so you can call this function repeatedly.


ULZTimerOff procedure

ZenTimer Unit

Stops the Long Period Zen Timer counting.

Declaration:

procedure ULZTimerOff;

Remarks:

Stops the Ultra Long Period Zen Timer counting and latches the count. Once you have stopped the timer you can read the count with ULZTimerCount.


ULZTimerOn procedure

ZenTimer Unit

Starts the Ultra Long Period Zen Timer counting.

Declaration:

procedure ULZTimerOn;

Remarks:

Starts the Ultra Long Period Zen Timer counting. Once you have started the timer, you can stop it with ULZTimerOff or you can latch the current count with ULZTimerLap.

The Ultra Long Period Zen Timer uses the available operating system services to obtain accurate timings results with as much precision as the operating system provides, but with enough granularity to time longer periods of time

than the Long Period Zen Timer. Note that the resolution of the timer ticks is not constant between different platforms, and you should use the ULZTimerResolution function to determine the number of seconds in a single tick of the timer, and use this to convert the timer counts to seconds.

Under 32-bit DOS, we use the system timer tick which runs at 18.2 times per second. Given that the timer count is returned as an unsigned 32-bit integer, this we can time intervals that are a maximum of 232 * (1/18.2) in length (or about 65,550 hours or 2731 days!).


ULZTimerResolution function

ZenTimer Unit

Returns the resolution of the Ultra Long Period Zen Timer.

Declaration:

function ULZTimerResolution: Real;

Remarks:

Returns the resolution of the Ultra Long Period Zen Timer as a floating point value measured in seconds per timer count. This function always returns 0.054925.


ZTimerInit procedure

ZenTimer Unit

Initializes the Zen Timer library.

Declaration:

procedure ZTimerInit;

Remarks:

This function initializes the Zen Timer library, and must be called before any of the remaining Zen Timer library functions are called.


IDE
IDE Overview

TMT Pascal compiler comes with an for Win32, which allows one to easily edit, compile and execute applications for any target.

Features

•	Tunable syntax highlighting.

•	Multi-level undo buffer.

•	Code templates.

•	Clipboard history window.

•	Comfortable multi-window editor, which allows one to edit and run sources.

•	Up to 10 bookmarks.

•	New Windows-based context-sensitive help system.

•	ANSI/OEM character insertion table.

•	Powerful search/replace engine, which allow to find specified text in open windows and directories.

•	Easy in use compiler options setup menu.

•	Multi-target compilation support.

Restrictions

Built-in debugger is not implemented in the current version of IDEW32.

See also:

Bookmarks

Code Templates

Compiler Options

Directories

Display

EditorEditor Shortcuts


Bookmarks

The Code Editor supports up to 10 bookmarks. Set your own bookmarks by right-clicking in the Code editor and choosing the toggle  Bookmarks. To jump to a bookmark, right-click and choose Goto Bookmarks. You can also toggle bookmark #0 by left-clicking on the left gutter.

The following bookmark operations shortcuts are available:

Shortcut                      Action

Shift+Ctrl+0	Sets bookmark 0

Shift+Ctrl+1	Sets bookmark 1

Shift+Ctrl+2	Sets bookmark 2

Shift+Ctrl+3	Sets bookmark 3

Shift+Ctrl+4	Sets bookmark 4

Shift+Ctrl+5	Sets bookmark 5

Shift+Ctrl+6	Sets bookmark 6

Shift+Ctrl+7	Sets bookmark 7

Shift+Ctrl+8	Sets bookmark 8

Shift+Ctrl+9	Sets bookmark 9

Shortcut                      Action

Ctrl+0	Goes to bookmark 0

Ctrl+1	Goes to bookmark 1

Ctrl+2	Goes to bookmark 2

Ctrl+3	Goes to bookmark 3

Ctrl+4	Goes to bookmark 4

Ctrl+5	Goes to bookmark 5

Ctrl+6	Goes to bookmark 6

Ctrl+7	Goes to bookmark 7

Ctrl+8	Goes to bookmark 8

Ctrl+9	Goes to bookmark 9


Code Templates
Code Templates (Options | Environment | Code Templates)

A set of templates is available to insert common programming statements into your code. Templates can be edited and added. While working in the Code Editor, press Ctrl+J to display the code templates defined.

To edit the name and description:

Select the name you want to edit. Click the Edit button. Edit the name and description fields as needed and click OK.

To edit a template:

When a name is selected, the code to be inserted in the file when the template is selected is displayed in the code window. Move  the cursor to the code window and edit the text as you desire.

To define the insertion point:

Place a vertical bar “|” in the code statement to define the point to begin insertion when the template is inserted in a code file. The cursor will be placed in the point  defined by the vertical bar.

To add a template:

Click Add button. After entering a Name and Description in the dialog box displayed, click OK.

To delete a template:

Select the name of the template you want to delete. Click Delete or press Del.


Compiler Options
Compiler Options (Options | Compiler)

Primary file

Specify the primary file to be used for the target executable file.

Active Window

Check this box to set a currently active window as primary file.

Word alignment data

Switches on/off word-alignment of variables and typed constants. Corresponds to ($A).

Strict var-strings

Controls type-checking on strings passed as variable parameters. Corresponds to ($V).

Range checking

Enables and disables the generation of range-checking code. Corresponds to ($R).

Objects and structures align

Switches on/off word-alignment of objects and structures. Corresponds to ($OA).

Debug information (MS-DOS target only)

Switches on/off  the generation of debug information. Corresponds to ($D).

I/O checking

Enables or disables the automatic code generation that checks the result of a call to an I/O procedure. Corresponds to ($I).

Local debug symbols (MS-DOS target only)

Enables or disables the generation of local symbol information. Corresponds to ($L).

Open string params

Controls the meaning of variable parameters declared using string keyword. Corresponds to ($P).

Overflow checking (Q)

Controls the generation of overflow checking code. Corresponds to ($Q).

Typed pointers

Controls the types of pointer values generated by the @ operator. Corresponds to ($T).

Show warnings

Switches on/off warnings generation. Corresponds to ($W).

Extended syntax

Enables or disables Turbo Pascal's extended syntax. Corresponds to ($X).

Extender logo (MS-DOS target only)

Switches on/off extender logo.

Complete Boolean eval

Switches on/off the two different models of code generation for the AND and OR Boolean operators. Corresponds to ($B).

Frame optimization

Switches on/off stack frame optimization. Corresponds to ($OPTFRM).

Registers optimization

Switches on/off register optimization. Corresponds to ($OPTREG).

Full optimization

Switches on/off full optimization (Frame optimization + Registers optimization). Corresponds to ($OPT).

C/C++ style comments

Switches on/off C/C++ style comments recognition. Corresponds to ($CC).

Ada-style comments

Aligns elements in structures to 32-bit boundaries. Corresponds to ($AC).

Intel MMX Assembler instructions

Enables/disables Intel MMX instructions support in built-in assembler. Corresponds to ($MMX).

AMD 3DNow! Assembler instructions

Enables/disables AMD 3DNow! Instructions support in built-in assembler. Corresponds to ($AMD).

Typed Inc/Dec operations

Enables/disables typed Inc/Dec operations on pointers. Corresponds to ($TPO).

Max EXE size

Specifies the maximum size of the executable module.

Stack size

Specifies the size of the application stack.

Max OBJ size

Specifies the size of the buffer for object modules (FPD/FPO/FPW-files). This parameter must be about one and a half times the size of the largest object module from the project.

Target (Multi-target Edition Only)

A drop-down box which allows one to select a target Operating System.


Directories
Directories (Options | Directories)

Use this page to specify directories, compiler and stub names. Click the “...” button to run directory browse window.

Root Path

Specifies directories where the TMT Pascal compiler has been installed. Default is C:\TMTPL.

Stub name

Name of the stub file to be linked with a generated application.

Resource Compiler

Specifies a name of the command-line resource compiler.

Compiler

Specifies a name of the command-line TMT Pascal compiler.

Source Path

Specifies directories where the compiler looks for source files when it cannot find them. Default is SRC:;SYS:..\UNITS.

Unit Path

Specifies directories where the compiler looks for RTL unit files when it cannot find them. Default is SRC:;SYS:..\UNITS.

OBJ Path

Specifies directories where the compiler looks for OBJ files when it cannot find them. Default is SRC:;SYS:..\UNITS.


Display
Display (Options | Environment | Display)

Use the Color page of the Environment Options dialog box to specify how the different elements of your code appear in the Code Editor.

You can specify foreground and background colors for anything listed in the Element list box. The sample Code Editor shows how your settings will appear in the Code Editor.

Display | General

Use the General page of the Environment Options dialog box to select display and font options for the Code Editor

Visible right margin

Check to display a line at the right margin of the Code Editor.

Right margin

Set the right margin of the Code Editor. The default is 80 characters.

Margin color

Select a color for the right margin.

Visible gutter

Check to display the gutter on the left edge of the Code Editor.

Gutter width

Set the width of the gutter in pixels.

Gutter color

Select a color for the gutter.

Left indent

Specify the left indent for the Editor.

Font name

Select a font type from the available screen fonts installed on your system (shown in the drop-down box). The Code Editor displays and uses only fixed size screen fonts. A sample text is displayed in the text box.

Font size

Select a Font name from the predefined font sizes associated with the font you selected in the Font list box. A sample text is displayed in the text box.

Display | Syntax Highlighting

Use the Syntax Highlighting page of the Environment Options/Display dialog box to specify the syntax highlighting scheme to be used in the Code Editor.

Element

Specifies syntax highlighting for a particular code element. You can choose from the Element list or click the element in the sample Code Editor.

Color scheme

Enables you to quickly configure the color scheme using predefined color combinations. The sample text box below shows how your settings will appear in the Code Editor. Predefined color schemes are the following: Defaults, Classic, Borland Delphi, Microsoft Visual Studio, Twilight, Ocean.

Foreground

Sets the foreground color for the selected code element.

Background

Sets the background color for the selected code element.


Editor
Editor (Options | Environment | Editor)

Use the Editor page of the Environment Options dialog box to customize the behavior of the Code Editor.

Keystroke mapping

Use the Keystroke mapping to configure the editor.

Overwrite blocks

Replaces a marked block of text with whatever is typed next. If Persistent Blocks is also selected, the text you enter is appended following the currently selected block.

Limit EOL

Limits the position of the cursor beyond the end-of-line character.

Force Cut and Copy enabled

Enables Edit|Cut and Edit|Copy, even when there is no text selected.

Undo after save

Allows you to retrieve changes after a save.

Find text at cursor

Places the text at the cursor into the Text To Find list box in the Find Text dialog box when you choose Search|Find. When this option is disabled you must type in the search text, unless the Text To Find list box is blank, in which case the editor still inserts the text at the cursor.

Highlight URLs

If URLs highlighting is enabled and if the text that is displayed in the Code Editor contains URLs then they will automatically be highlighted. Please notice that if the URL is highlighted then users can click on it and browse the corresponding Web location with the installed browser.

Double click line

Highlights the line when you double-click any character in the line. If disabled, only the selected word is highlighted.

Auto Indent mode

Positions the cursor under the first nonblank character of the preceding nonblank line when you press Enter.

Backspace unindents

Aligns the insertion point to the previous indentation level (outdents it) when you press Backspace, if the cursor is on the first nonblank character of a line.

Smart tab

Tabs to the first non-whitespace character in the preceding line. If Use Tab Character is enabled, this option is off.

Disable dragging

Disables text dragging feature.

Persistent blocks

Keeps marked blocks selected even when the cursor is moved, until a new block is selected.

Use syntax highlighting

Enables syntax highlighting. To set highlighting options, use the Colors page

Allow overwrite caret shape

Allows overwrite caret shape, when insert mode is disabled.

Enable group undo

Undoes your last editing command as well as any subsequent editing commands of the same type, if you press Alt+Backspace or choose Edit|Undo.

Select text only

Limits a selection by the cursor to the end-of-line character.

Cursor beyond EOF

Positions the cursor beyond the end-of-file character.

Use system clipboard history

Allows the Code Editor to use the system clipboard.

Max horizontal pos

Specifies the maximum horizontal position in the Code Editor.

Spaces in tabs

Specifies the spaces number in the tabs.

Block indent

Specifies the number of spaces to indent a marked block. The default is 2.

Tab Stops

Sets the character columns that the cursor will move to each time you press Tab.


Editor Shortcuts

Shortcut                     Action or command

F1, Ctrl + F1	Topic Search
F3	Search|Search Again
F6	Displays the next window
Shift+F6	Displays the previous window
Ctrl+I	Inserts a tab
Ctrl+L	Search|Search Again
Ctrl+J	Displays the code templates box
Ctrl+N	Inserts a new line
Ctrl+R	Search|Replace
Ctrl+S	File|Save
Ctrl+T	Deletes a word right
Ctrl+V	Edit|Insert
Ctrl+W	Deletes a word left
Ctrl+Y	Deletes a line
Ctrl+Z	Edit|Undo
Shift+Ctrl+Z	Edit|Redo
End	Moves to the end of a line
Home	Moves to the start of a line
Enter	Inserts a carriage return
Ins	Turns insert mode on/off
Del	Deletes the character to the right of the cursor
Backspace	Deletes the character to the left of the cursor
Tab	Inserts a tab
Space	Inserts a blank space
Left Arrow	Moves the cursor left one column, accounting for the autoindent setting
Right Arrow	Moves the cursor right one column, accounting for the autoindent setting
Up Arrow	Moves up one line
Down Arrow	Moves down one line
Page Up	Moves up one page
Page Down	Moves down one page
Ctrl+Alt+F	Searches word at cursor
Ctrl+Left Arrow	Moves one word left
Ctrl+Right Arrow	Moves one word right
Ctrl+Home	Moves to the top of a screen
Ctrl+End	Moves to the end of a screen
Ctrl+PgDn	Moves to the bottom of a file
Ctrl+PgUp	Moves to the top of a file
Ctrl+Backspace	Move one word to the right
Ctrl+Space	Inserts a blank space
Ctrl+Enter	Opens file at cursor
Ctrl+Tab	Moves to the next page
Ctrl+Shift+I	Indents Block
Ctrl+Shift+U	Outdents Block
Ctrl+Shift+Y	Deletes to the end of line
Shift+Tab	Inserts a tab
Shift+Backspace	Deletes the character to the left of the cursor
Shift+Left Arrow	Selects the character to the left of the cursor
Shift+Right Arrow	Selects the character to the right of the cursor
Shift+Up Arrow	Moves the cursor up one line and selects from the left of the starting cursor position
Shift+Down Arrow	Moves the cursor down one line and selects from the right of the starting cursor position
Shift+PgUp	Moves the cursor up one screen and selects from the left of the starting cursor position
Shift+PgDn	Moves the cursor down one line and selects from the right of the starting cursor position
Shift+End	Selects from the cursor position to the end of the current line
Shift+Home	Selects from the cursor position to the start of the current line
Shift+Space	Inserts a blank space
Shift+Enter	Inserts a new line with a carriage return
Shift+Ctrl+Tab	Moves to the previous page
Ctrl+Shift+Left Arrow	Selects the word to the left of the cursor
Ctrl+Shift+Right Arrow	Selects the word to the right of the cursor
Ctrl+Shift+Home	Selects from the cursor position to the start of the current file
Ctrl+Shift+End	Selects from the cursor position to the end of the current file
Ctrl+Shift+PgDn	Selects from the cursor position to the bottom of the screen
Ctrl+Shift+PgUp	Selects from the cursor position to the top of the screen
Ctrl+Shift+Tab	Moves to the previous page
Alt+Backspace	Edit|Undo

Hint:

When selecting, hold Alt to select a vertical block.

See also:

Bookmarks


PMODE/W DOS Extender

TMT Pascal uses the PMODEW v1.33 based extender. This chapter of the HELP file is based on the original manual Copyright (c) 1994-1997, by Charles Scheffold and Thomas Pytel. All rights reserved. All trademarks used in this documentation are property of their respective owners.

About PMODE/W

Supported DPMI INT 31h functions


About PMODE/W

PMODE/W allows DOS programs to run in full 32 bit protected mode, with access to all memory available in the system. PMODE/W basically extends the DOS environment to protected mode and provides a simple interface to the real mode DOS system services for your code. PMODE/W takes care of all aspects of running the system in protected mode and maintaining compatibility with the underlying real mode software. PMODE/W deals with low level necessities such as descriptor tables, memory management, IRQ and interrupt redirection, real/protected mode translation functions, exception handling, and other miscellaneous aspects of running in protected mode. Your code does not need to deal with specific aspects of different systems, such as XMS/EMS/VCPI/DPMI availability. PMODE/W will run on top of almost any system and provide common protected mode services to your program through the DPMI interface specification, as well as most standard DOS functions extended for protected mode use.

PMODE/W is the stub and extender in one. The generated executable contains the PMODE/W extender within it as the stub. When run, PMODE/W will take care of setting up the system and executing the protected mode portion of the program. Several years have gone into the development of PMODE/W. It is now a fairly mature DOS extender, and has gone through its fair share of bugs and incompatibilities. It is at this point, a very stable protected mode system. Great pains have gone into the optimization and testing of PMODE/W. Our major goals have been speed, size, and stability. We now feel that we have achieved a good deal of those things. But don't take our word for it, try it yourself, as you can do that very easily before you actually decide to buy PMODE/W. Just plug PMODE/W into any popular program out there which uses DOS/4GW.

To sum it up, if you are looking for a good solid, stable, and fast extender, PMODE/W may be just what you need.

Here are the advantages of PMODE/W:

No external extender required (everything needed to execute is in the EXE). Small size (less than 12k for the entire extender program). Compression of protected mode executables. Low extended memory overhead. Does not require ANY extended memory to load OR execute. Fast execution.

Our major concerns in developing PMODE/W were speed, size, and stability. PMODE/W itself was written entirely in assembly. When running under PMODE/W, your code will be running at a privilege level of zero, the highest and fastest. PMODE/W does not virtualize what it does not need to, and does not invoke any protected mode mechanism that is slow. For example, if the system is running clean or under XMS, PMODE/W does not turn on paging. Under a memory manager which provides both VCPI and DPMI services, PMODE/W will opt for VCPI protected mode which is significantly faster than DPMI. When PMODE/W makes calls to real mode, it switches the system into actual real mode rather than the slower V86 mode (when it can, under VCPI this is not possible, control must be passed back to the VCPI server). In terms of speed, when your code is running under PMODE/W, it is running as fast as the system will allow. In terms of size on disk, we need say no more than for you to look at the size of the PMODE/W executable and compare it to other extenders. In terms of memory size, you may do tests yourself to confirm that PMODE/W does indeed suck up a lot less memory at run-time than the competition. In fact, PMODE/W will run even if there is absolutely no extended memory in the system (assuming of course there is enough low memory for the program). To be fair, we must say that we squished the PMODE/W executable with our own compression program written expressly for the purpose. This demonstrates the extent we took most of our optimizations to.

When run under a clean system, XMS, or VCPI, PMODE/W has control of protected mode. In this case, it can set up the system to run as fast as possible under the various conditions. Under DPMI, the DPMI host of the system will have full protected mode control and PMODE/W will install its DOS extensions on top of that. If the system provides both VCPI and DPMI services, PMODE/W will use the VCPI services for faster execution, unless instructed not to by the setup program. When PMODE/W does have protected mode control under clean/XMS/VCPI, it runs all code at a privilege level of zero. In addition, under a clean or XMS system, paging will not be enabled. This is only a minor speed increase, but there is no real need to manage paging.

PMODE/W provides a subset of DPMI 0.9 function calls and general functionality when a DPMI host is not present. PMODE/W will pass any software interrupts from protected mode to their default real mode handlers, provided no protected mode handlers have been installed for them, just as DPMI will. The general registers will be passed on to the real mode handler, but the segment registers can not be as they have different meanings in real mode and protected mode. The flags will be passed back from the real mode handler. This provides a simple interface to all real mode interrupt routines which do not take parameters in the segment registers, for example, INT 16h function 00h.

Any IRQs that occur in protected mode and have not been hooked by a protected mode handler will be sent on to their real mode handlers. If an IRQ occurs in real mode, and a protected mode handler has hooked that IRQ, it will be sent to the protected mode handler first. The protected mode handler may chain to the real mode handler for that IRQ by calling the previous protected mode handler for that IRQ. This behavior is in accordance with the DPMI standard. If you hook a protected mode IRQ (INT 31h function 0205h), then hook the same IRQ in real mode (INT 31h function 0201h), the protected mode handler will be called if the IRQ occurs in protected mode, and the real mode handler will handle the IRQs if they occur in real mode. Setting up two handlers like this assures minimal latency. This means a handler will get control when the IRQ occurs as soon as physically possible. PMODE/W does have to intervene in the IRQ process, however, when the low 8 IRQs are mapped to INTs 08h-15h to differentiate IRQs from CPU exceptions.

In accordance with DPMI specifications, PMODE/W will pass up software interrupts 1ch (BIOS timer tick), 23h (DOS CTRL+C), and 24h (DOS critical error) from real mode to protected mode. This means that those interrupts can be hooked directly in protected mode without having to set up a callback mechanism yourself. PMODE/W will also pass interrupt 1bh (BIOS CTRL+BREAK) from real mode up to protected mode. This is not a DPMI requirement, but it is necessary for the sake of compatibility with DOS/4GW. Another departure by PMODE/W from official DPMI specifications is in extended memory allocation. DPMI documentation states that the block of extended memory allocated through function 0501h is guaranteed at least paragraph alignment. The PMODE/W DPMI implementation will enforce only DWORD alignment.

When a PMODE/W executable is run, PMODE/W will attempt to switch the system into protected mode and load the protected mode portion of the same executable. If there is some error, not enough memory, or a system incompatibility, PMODE/W will exit with an error message. If loading was successful, PMODE/W will pass execution control on to the program. PMODE/W will load any 16 bit code and data into low memory, but 32 bit code and data may be loaded into low or extended memory depending on availability.

There are a number of modifiable parameters in the PMODE/W extender executable that affect protected mode execution. For the most part, these parameters deal with memory. PMODE/W allocates one large block of extended memory for its pool from which it provides memory to its client program. There is a maximum value for the extended memory to be allocated. By default, the maximum is all of the extended memory in the system. The maximum value reflects the size of the block you want PMODE/W to take from the system, not necessarily the size of the largest block available to the default GetMem procedures. You may set the maximum to zero to indicate you do not want PMODE/W to allocate ANY extended memory. The amount of memory that you allow PMODE/W to allocate from the system determines how much extended memory will be left to other if you shell out of your PMODE/W program.

Another variable specifies the amount of low memory for PMODE/W to TRY to keep free. If PMODE/W can, it will accommodate this value by loading 32 bit code and data into extended memory. If there is not enough extended memory available for this, 32 bit code and data will be loaded into low memory anyway. If PMODE/W can not keep this much low memory free, it will not exit with an error message. Setting this parameter to a high value will, in effect, duplicate the DOS/4GW behavior of loading all 32 bit code and data into extended memory. If you do not necessarily need any extra low memory free during the execution of your program, you may set this value to zero.

There is a group of parameters that specify the number and size of nested mode switch stacks. Whenever you make a call to real mode, or a callback or IRQ is passed from real mode to its routine in protected mode, a nested stack is used. These parameters have meaning only if the program is not run under a DPMI system. If a DPMI host is in place when the program is run, it provides its own nested stacks for mode switches. The number of nested stacks directly affects the number of nested mode switches your program can make using the various mode switch methods. The size of both the real mode and protected mode nested stacks can also be specified. By default, these values are high enough for normal operation. However, if you intend to use a lot of stack variables in a protected mode IRQ handler, or a lot of recursive calls, you may need to increase the size of the protected mode nested stacks. The more nested stacks you specify, and the larger they are, the more low memory is needed by PMODE/W during execution.

Another group of variables that has meaning only under clean/XMS/VCPI execution specify the number of selectors and DPMI callbacks you want PMODE/W to make available. The more selectors and callbacks you ask for, the more low memory is used by PMODE/W, though the amount of low memory used for each is quite low so that large numbers of each can be specified. There will usually be a little less than the number of selectors and callbacks you request available to your program due to the protected mode system and Pascal code using some of them. For this reason you should request 20h-40h more selectors and 2-4 more callbacks than you will need in your program.

There are four other miscellaneous parameters that can be set. There is a maximum number of page tables to use under a VCPI system. Each page table allocated requires 4k of low memory to be used by PMODE/W and maps 4M of memory. This directly affects the maximum amount of extended memory available under a VCPI system. This parameter is only the maximum number of page tables to allow. At run-time, only as many page tables will be allocated as are needed. Under a clean/XMS system, no page tables are required, so this parameter has no meaning. But under VCPI, you may want to restrict the number of page tables to save low memory if you do not need more than a certain amount of extended memory. This puts a maximum ceiling on extended memory under VCPI which may be lower than the maximum actually specified in the other variable. The second parameter specifies the order of DPMI and VCPI detection. By default, VCPI will be checked before DPMI, but you may set DPMI to be checked before VCPI so that under a system which supports both VCPI and DPMI, DPMI will be used. The third variable specifies how many pages to reserve for physical address mapping calls (INT 31h function 0800h) under VCPI. Under XMS or a clean system, paging is not enabled, and PMODE/W does not need pages for physical address mapping. Each page will allow you to map up to 4M of address space and takes up 4k of extended memory. So for example, if you intend to map a 2M frame buffer of a video card, you will need only one page. You may set this parameter to zero if you do not intend to map any physical addresses. The fourth parameter specifies whether PMODE/W displays its banner at startup. This may be desirable to indicate that the program is indeed running, and has not crashed, as allocating memory from certain VCPI servers can be a slow process.


Supported DPMI INT 31h functions

PMODE/W duplicates a subset of DPMI protected mode functions. These functions are available ONLY in protected through INT 31h. They provide descriptor services, extended memory services, interrupt services, translation services, and some other miscellaneous things. A function is called by setting AX to the function code, setting any other registers for the function, and executing INT 31h. Upon return, the carry flag will be clear if the function was successful. If the carry flag is set, the function failed. All other registers are preserved unless otherwise specified. In addition to the functions listed here, functions 0600h, 0601h, 0702h, and 0703h will return with the carry flag clear to stay compatible with code that uses those particular DPMI functions.

Function 0000h - Allocate Descriptors

Function 0001h - Free Descriptor

Function 0002h - Segment to Descriptor

Function 0003h - Get Selector Increment Value

Function 0006h - Get Segment Base Address

Function 0007h - Set Segment Base Address

Function 0008h - Set Segment Limit

Function 0009h - Set Descriptor Access Rights

Function 000Ah - Create Alias Descriptor

Function 000Bh - Get Descriptor

Function 000Ch - Set Descriptor

Function 0100h - Allocate DOS Memory Block

Function 0101h - Free DOS Memory Block

Function 0102h - Resize DOS Memory Block

Function 0200h - Get Real Mode Interrupt Vector

Function 0201h - Set Real Mode Interrupt Vector

Function 0202h - Get Processor Exception Handler Vector

Function 0203h - Set Processor Exception Handler Vector

Function 0204h - Get Protected Mode Interrupt Vector

Function 0205h - Set Protected Mode Interrupt Vector

Function 0300h - Simulate Real Mode Interrupt

Function 0301h - Call Real Mode Procedure With Far Return Frame

Function 0302h - Call Real Mode Procedure With IRET Frame

Function 0303h - Allocate Real Mode Callback Address

Function 0304h - Free Real Mode Callback Address

Function 0305h - Get State Save/Restore Addresses

Function 0306h - Get Raw Mode Switch Addresses

Function 0400h - Get Version

Function 0500h - Get Free Memory Information

Function 0501h - Allocate Memory Block

Function 0502h - Free Memory Block

Function 0503h - Resize Memory Block

Function 0800h - Physical Address Mapping

Function 0801h - Free Physical Address Mapping

Function 0900h - Get and Disable Virtual Interrupt State

Function 0901h - Get and Enable Virtual Interrupt State

Function 0902h - Get Virtual Interrupt State

Function EEFFh - Get DOS Extender Information


Function 0000h - Allocate Descriptors

PMODE/W API

Allocates one or more descriptors in the client's descriptor table. The descriptor(s) allocated must be initialized by the application with other function calls.

In:

AX =    0000h

CX = number of descriptors to allocate

Out:

if successful:

  carry flag clear

  AX     = base selector

if failed:

  carry flag set

Notes:

- If more that one descriptor was requested, the function returns a base selector referencing the first of a contiguous array of descriptors. The selector values for subsequent descriptors in the array can be calculated by adding the value returned by INT 31h function 0003h.

- The allocated descriptor(s) will be set to expand-up writeable data, with the present bit set and a base and limit of zero. The privilege level of the descriptor(s) will match the client's code segment privilege level.


Function 0001h - Free Descriptor

PMODE/W API

Frees a descriptor.

In:

  AX =    0001h

  BX =    selector for the descriptor to free

Out:

  if successful:

    carry flag clear

  if failed:

    carry flag set

Notes:

- Each descriptor allocated with INT 31h function 0000h must be freed individually with the function. Even if it was previously allocated as part of a contiguous array of descriptors.

- Under DPMI 1.0/VCPI/XMS/raw, any segment registers which contain the selector being freed are zeroed by this function.


Function 0002h - Segment to Descriptor

PMODE/W API

Converts a real mode segment into a protected mode descriptor.

In:

  AX =    0002h

  BX =    real mode segment

Out:

  if successful:

    carry flag clear

    AX =  selector

  if failed:

    carry flag set

Notes:

Multiple calls for the same real mode segment return the same selector. The returned descriptor should never be modified or freed.


Function 0003h - Get Selector Increment Value
Function 0003 - Get Selector Increment Value

PMODE/W API

The Allocate Descriptors function (0000h) can allocate an array of contiguous descriptors, but only return a selector for the first descriptor. The value returned by this function can be used to calculate the selectors for subsequent descriptors in the array.

In:

  AX =     0003h

Out:

  always successful:

    carry flag clear

    AX =  selector increment value

Notes:

The increment value is always a power of two.


Function 0006h - Get Segment Base Address
Function 0006 - Get Segment Base Address

PMODE/W API

Returns the 32bit linear base address from the descriptor table for the specified segment.

In:

  AX =     0006h

  BX =     selector

Out:

  if successful:

    carry flag clear

    CX:DX  = 32bit linear base address of segment

  if failed:

    carry flag set

Notes:

Client programs must use the LSL instruction to query the limit for a descriptor.


Function 0007h - Set Segment Base Address
Function 0007 - Set Segment Base Address

PMODE/W API

Sets the 32bit linear base address field in the descriptor for the specified segment.

In:

  AX    = 0007h

  BX    = selector

  CX:DX = 32bit linear base address of segment

Out:

  if successful:

    carry flag clear

  if failed:

    carry flag set

Notes:

Under DPMI 1.0/VCPI/XMS/raw, any segment register which contains the selector specified in register BX will be reloaded. DPMI 0.9 may do this, but it is not guaranteed. We hope you have enough sense not to try to modify your current CS or SS descriptor.


Function 0008h - Set Segment Limit
Function 0008 - Set Segment Limit

PMODE/W API

Sets the limit field in the descriptor for the specified segment.

In:

  AX =    0008h

  BX =    selector

  CX:DX = 32bit segment limit

Out:

  if successful:

   carry flag clear

  if failed:

   carry flag set

Notes:

The value supplied to the function in CX:DX is the byte length of the segment-1. Segment limits greater than or equal to 1M must be page aligned. That is, they must have the low 12 bits set.

This function has an implicit effect on the "G" bit in the segment's descriptor. Client programs must use the LSL instruction to query the limit for a descriptor.

Under DPMI 1.0/VCPI/XMS/raw, any segment register which contains the selector specified in register BX will be reloaded. DPMI 0.9 may do this, but it is not guaranteed. We hope you have enough sense not to try to modify your current CS or SS descriptor.


Function 0009h - Set Descriptor Access Rights
Function 0009 - Set Descriptor Access Rights

PMODE/W API

Modifies the access rights field in the descriptor for the specified segment.

In:

  AX     = 0009h

  BX     = selector

  CX     = access rights/type word

Out:

  if successful:

    carry flag clear

  if failed:

    carry flag set

Notes:

The access rights/type word passed to the function in CX has the following format:

  G   - 0=byte granular, 1=page granular

  B/D - 0=default 16bit, 1=default 32bit

  DPL - must be equal to caller's CPL

  C/D - 0=data, 1=code

  E/C - data: 0=expand-up, 1=expand-down

        code: must be 0 (non-conforming)

  W/R - data: 0=read, 1=read/write

        code: must be 1 (readable)

  A   - 0=not accessed, 1=accessed

  0   - must be 0

  1   - must be 1

  ?   - ignored

Client programs should use the LAR instruction to examine the access rights of a descriptor.

Under DPMI 1.0/VCPI/XMS/raw, any segment register which contains the selector specified in register BX will be reloaded. DPMI 0.9 may do this, but it is not guaranteed.

We hope you have enough sense not to try to modify your current CS or SS descriptor.


Function 000A- Create Alias Descriptor

PMODE/W API

Creates a new data descriptor that has the same base and limit as the specified descriptor.

In:

  AX     = 000ah

  BX     = selector

Out:

  if successful:

    carry flag clear

    AX     = data selector (alias)

  if failed:

    carry flag set

Notes:

The selector supplied to the function may be either a data descriptor or a code descriptor. The alias descriptor created is always an expand-up writeable data segment.

The descriptor alias returned by this function will not track changes to the original descriptor.


Function 000B - Get Descriptor
Function 000B Get Descriptor

PMODE/W API

Copies the descriptor table entry for the specified selector into an 8 byte buffer.

In:

  AX     = 000bh

  BX     = selector

  ES:EDI = selector:offset of 8 byte buffer

Out:

  if successful:

    carry flag clear

    buffer pointed to by ES:EDI contains descriptor

  if failed:

    carry flag set


Function 000C - Set Descriptor
Function 000C Set Descriptor

PMODE/W API

Copies the contents of an 8 byte buffer into the descriptor for the specified selector.

In:

  AX     = 000ch

  BX     = selector

  ES:EDI = selector:offset of 8 byte buffer containing descriptor

Out:

  if successful:

    carry flag clear

  if failed:

    carry flag set

Notes:

The descriptors access rights/type word at offset 5 within the descriptor follows the same format and restrictions as the access rights/type parameter CX to the Set Descriptor Access Rights function (0009h).

Under DPMI 1.0/VCPI/XMS/raw, any segment register which contains the selector specified in register BX will be reloaded. DPMI 0.9 may do this, but it is not guaranteed.

We hope you have enough sense not to try to modify your current CS or SS descriptor or the descriptor of the buffer.


Function 0100 - Allocate DOS Memory Block
Function 0100 Allocate DOS Memory Block

PMODE/W API

Allocates low memory through DOS function 48h and allocates it a descriptor.

In:

  AX     = 0100h

  BX     = paragraphs to allocate

Out:

  if successful:

    carry flag clear

    AX     = real mode segment address

    DX     = protected mode selector for memory block

  if failed:

    carry flag set

    AX     = DOS error code

    BX     = size of largest available block


Function 0101 - Free DOS Memory Block
Function 0101 Free DOS Memory Block

PMODE/W API

Frees a low memory block previously allocated by function 0100h.

In:

  AX     = 0101h

  DX     = protected mode selector for memory block

Out:

  if successful:

    carry flag clear

  if failed:

    carry flag set

    AX     = DOS error code


Function 0102 - Resize DOS Memory Block
Function 0102 Resize DOS Memory Block

PMODE/W API

Resizes a low memory block previously allocated by function 0100h.

In:

  AX     = 0102h

  BX     = new block size in paragraphs

  DX     = protected mode selector for memory block

Out:

  if successful:

    carry flag clear

  if failed:

    carry flag set

    AX     = DOS error code

    BX     = size of largest available block


Function 0200 - Get Real Mode Interrupt Vector
Function 0200 Get Real Mode Interrupt Vector

PMODE/W API

Returns the real mode segment:offset for the specified interrupt vector.

In:

  AX    = 0200h

  BL    = interrupt number

Out:

  always successful:

    carry flag clear

    CX:DX = segment:offset of real mode interrupt handler

Notes:

The value returned in CX is a real mode segment address, not a protected mode selector.


Function 0201 - Set Real Mode Interrupt Vector
Function 0201 Set Real Mode Interrupt Vector

PMODE/W API

Sets the real mode segment:offset for the specified interrupt vector.

In:

  AX     = 0201h

  BL     = interrupt number

  CX:DX  = segment:offset of real mode interrupt handler

Out:

  always successful:

    carry flag clear

Notes:

The value passed in CX must be a real mode segment address, not a protected mode selector. Consequently, the interrupt handler must either reside in DOS memory (below the 1M boundary) or the client must allocate a real mode callback address.


Function 0202 - Get Processor Exception Handler Vector
Function 0202 Get Processor Exception Handler Vector

PMODE/W API

Returns the address of the current protected mode exception handler for the specified exception number.

In:

  AX     = 0202h

  BL     = exception number (00h-1fh)

Out:

  if successful:

    carry flag clear

    CX:EDX = selector:offset of exception handler

  if failed:

    carry flag set

Notes:

PMODE/W handles exceptions under clean/XMS/VCPI environments. Under a   DPMI environment, exception handling is provided by the DPMI host.

PMODE/W only traps exceptions 0 through 14. The default behavior is to terminate execution and do a debug dump. PMODE/W will terminate on exceptions 0, 1, 2, 3, 4, 5, and 7, instead of passing them down to the real mode handlers as DPMI specifications state.


Function 0203 - Set Processor Exception Handler Vector
Function 0203 Set Processor Exception Handler Vector

PMODE/W API

Sets the address of a handler for a CPU exception or fault, allowing a protected mode application to intercept processor exceptions.

In:

  AX     = 0203h

  BL     = exception number (00h-1fh)

  CX:EDX = selector:offset of exception handler

Out:

  if successful:

    carry flag clear

  if failed:

    carry flag set

Notes:

PMODE/W handles exceptions under clean/XMS/VCPI environments. Under a  DPMI environment, exception handling is provided by the DPMI host.

PMODE/W only traps exceptions 0 through 14. The default behavior is to terminate execution and do a debug dump. PMODE/W will terminate on exceptions 0, 1, 2, 3, 4, 5, and 7, instead of passing them down to the real mode handlers as DPMI specifications state.

If you wish to hook one of the low 8 interrupts, you must hook it as an exception. It will not be called if you hook it with function 0205h.


Function 0204 - Get Protected Mode Interrupt Vector
Function 0204 Get Protected Mode Interrupt Vector

PMODE/W API

Returns the address of the current protected mode interrupt handler for the specified interrupt.

In:

  AX     = 0204h

  BL     = interrupt number

Out:

  always successful:

    carry flag clear

    CX:EDX = selector:offset of protected mode interrupt handler

Notes:

The value returned in CX is a valid protected mode selector, not a real mode segment address.


Function 0205 - Set Protected Mode Interrupt Vector
Function 0205 Set Protected Mode Interrupt Vector

PMODE/W API

Sets the address of the protected mode interrupt handler for the specified interrupt.

In:

  AX     = 0205h

  BL     = interrupt number

  CX:EDX = selector offset of protected mode interrupt handler

Out:

  if successful:

    carry flag clear

  if failed:

    carry flag set

Notes:

The value passed in CX must be a valid protected mode selector, not a real mode segment address.

If you wish to hook one of the low 8 interrupts, you must hook it as an exception. It will not be called if you hook it with function 0205h.


Function 0300 - Simulate Real Mode Interrupt
Function 0300 Simulate Real Mode Interrupt

PMODE/W API

Simulates an interrupt in real mode. The function transfers control to the address specified by the real mode interrupt vector. The real mode handler must return by executing an IRET.

In:

  AX     = 0300h

  BL     = interrupt number

  BH     = must be 0

  CX     = number of words to copy from the protected mode stack to the real mode stack

  ES:EDI = selector:offset of real mode register data structure in the following format:

    Offset  Length  Contents

    00h     4       EDI

    04h     4       ESI

    08h     4       EBP

    0ch     4       reserved, ignored

    10h     4       EBX

    14h     4       EDX

    18h     4       ECX

    1ch     4       EAX

    20h     2       CPU status flags

    22h     2       ES

    24h     2       DS

    26h     2       FS

    28h     2       GS

    2ah     2       IP (reserved, ignored)

    2ch     2       CS (reserved, ignored)

    2eh     2       SP

    30h     2       SS

Out:

  if successful:

    carry flag clear

    ES:EDI = selector offset of modified real mode register data structure

  if failed:

    carry flag set

Notes:

The CS:IP in the real mode register data structure is ignored by this function. The appropriate interrupt handler will be called based on the value passed in BL.

If the SS:SP fields in the real mode register data structure are zero, a real mode stack will be provided by the host. Otherwise the real mode SS:SP will be set to the specified values before the interrupt handler is called.

The flags specified in the real mode register data structure will be put on the real mode interrupt handler's IRET frame. The interrupt handler will be called with the interrupt and trace flags clear.

Values placed in the segment register positions of the data structure must be valid for real mode. That is, the values must be paragraph addresses, not protected mode selectors.

The target real mode handler must return with the stack in the same state as when it was called. This means that the real mode code may switch stacks while it is running, but must return on the same stack that it was called on and must return with an IRET.

When this function returns, the real mode register data structure will contain the values that were returned by the real mode interrupt handler. The CS:IP and SS:SP values will be unmodified in the data structure.

It is the caller's responsibility to remove any parameters that were pushed on the protected mode stack.


Function 0301 - Call Real Mode Procedure With Far Return Frame
Function 0301 Call Real Mode Procedure With Far Return Frame

PMODE/W API

Simulates a FAR CALL to a real mode procedure. The called procedure must return by executing a RETF instruction.

In:

  AX     = 0301h

  BH     = must be 0

  CX     = number of words to copy from the protected mode stack to the real mode stack

  ES:EDI = selector:offset of real mode register data structure in the following format:

    Offset  Length  Contents

    00h     4       EDI

    04h     4       ESI

    08h     4       EBP

    0ch     4       reserved, ignored

    10h     4       EBX

    14h     4       EDX

    18h     4       ECX

    1ch     4       EAX

    20h     2       CPU status flags

    22h     2       ES

    24h     2       DS

    26h     2       FS

    28h     2       GS

    2ah     2       IP

    2ch     2       CS

    2eh     2       SP

    30h     2       SS

Out:

  if successful:

    carry flag clear

    ES:EDI = selector offset of modified real mode register data structure

  if failed:

    carry flag set

Notes:

The CS:IP in the real mode register data structure specifies the address of the real mode procedure to call.

If the SS:SP fields in the real mode register data structure are zero, a real mode stack will be provided by the host. Otherwise the real mode SS:SP will be set to the specified values before the procedure is called.

Values placed in the segment register positions of the data structure must be valid for real mode. That is, the values must be paragraph addresses, not protected mode selectors.

The target real mode procedure must return with the stack in the same state as when it was called. This means that the real mode code may switch stacks while it is running, but must return on the same stack that it was called on and must return with a RETF and should not clear the stack of any parameters that were passed to it on the stack.

When this function returns, the real mode register data structure will contain the values that were returned by the real mode procedure. The CS:IP and SS:SP values will be unmodified in the data structure.

It is the caller's responsibility to remove any parameters that were pushed on the protected mode stack.


Function 0302 - Call Real Mode Procedure With IRET Frame
Function 0302 Call Real Mode Procedure With IRET Frame

PMODE/W API

Simulates a FAR CALL with flags pushed on the stack to a real mode routine. The real mode procedure must return by executing an IRET instruction or a RETF 2.

In:

  AX     = 0302h

  BH     = must be 0

  CX     = number of words to copy from the protected mode stack to the real mode stack

  ES:EDI = selector:offset of real mode register data structure in the following format:

    Offset  Length  Contents

    00h     4       EDI

    04h     4       ESI

    08h     4       EBP

    0ch     4       reserved, ignored

    10h     4       EBX

    14h     4       EDX

    18h     4       ECX

    1ch     4       EAX

    20h     2       CPU status flags

    22h     2       ES

    24h     2       DS

    26h     2       FS

    28h     2       GS

    2ah     2       IP

    2ch     2       CS

    2eh     2       SP

    30h     2       SS

Out:

  if successful:

    carry flag clear

    ES:EDI = selector offset of modified real mode register data structure

  if failed:

    carry flag set

Notes:

The CS:IP in the real mode register data structure specifies the address of the real mode procedure to call.

If the SS:SP fields in the real mode register data structure are zero, a real mode stack will be provided by the host. Otherwise the real mode SS:SP will be set to the specified values before the procedure is called.

The flags specified in the real mode register data structure will be put on the real mode procedure's IRET frame. The procedure will be called with the interrupt and trace flags clear.

Values placed in the segment register positions of the data structure must be valid for real mode. That is, the values must be paragraph addresses, not protected mode selectors.

The target real mode procedure must return with the stack in the same state as when it was called. This means that the real mode code may switch stacks while it is running, but must return on the same stack that it was called on and must return with an IRET or discard the flags from the stack with a RETF 2 and should not clear the stack of any parameters that were passed to it on the stack.

When this function returns, the real mode register data structure will contain the values that were returned by the real mode procedure. The CS:IP and SS:SP values will be unmodified in the data structure.

It is the caller's responsibility to remove any parameters that were pushed on the protected mode stack.


Function 0303 - Allocate Real Mode Callback Address
Function 0303 Allocate Real Mode Callback Address

PMODE/W API

Returns a unique real mode segment:offset, known as a "real mode callback", that will transfer control from real mode to a protected mode procedure. Callback addresses obtained with this function can be passed by a protected mode program to a real mode application, interrupt handler, device driver, TSR, etc... so that the real mode program can call procedures within the protected mode program.

In:

  AX     = 0303h

  DS:ESI = selector:offset of protected mode procedure to call

  ES:EDI = selector:offset of 32h byte buffer for real mode register data structure to be used when calling the callback routine.

Out:

  if successful:

    carry flag clear

    CX:DX  = segment:offset of real mode callback

  if failed:

    carry flag set

Notes:

A descriptor may be allocated for each callback to hold the real mode SS descriptor. Real mode callbacks are a limited system resource. A client should release a callback that it is no longer using.


Function 0304 - Free Real Mode Callback Address
Function 0304 Free Real Mode Callback Address

PMODE/W API

Releases a real mode callback address that was previously allocated with the Allocate Real Mode Callback Address function (0303h).

In:

  AX     = 0304h

  CX:DX  = segment:offset of real mode callback to be freed

Out:

  if successful:

    carry flag clear

  if failed:

    carry flag set

Notes:

Real mode callbacks are a limited system resource. A client should release any callback that it is no longer using.


Function 0305 - Get State Save/Restore Addresses
Function 0305 Get State Save/Restore Addresses

PMODE/W API

Returns the address of two procedures used to save and restore the state of the current task's registers in the mode (protected or real) which is not currently executing.

In:

  AX     = 0305h

Out:

  always successful:

    carry flag clear

    AX     = size of buffer in bytes required to save state

    BX:CX  = segment:offset of real mode routine used to save/restore state

    SI:EDI = selector:offset of protected mode routine used to save/restore state

Notes:

_ The real mode segment:offset returned by this function should be called only in real mode to save/restore the state of the protected mode register The protected mode selector:offset returned by this function should be called only in protected mode to save/restore the state of the real mode registers.

Both of the state save/restore procedures are entered by a FAR CALL with the following parameters:

  AL       = 0 to save state

           = 1 to restore state

  ES:(E)DI = (selector or segment):offset of state buffer

The state buffer must be at least as large as the value returned in AX by INT 31h function 0305h. The state save/restore procedures do not modify an registers. DI must be used for the buffer offset in real mode, EDI must be used in protected mode.

Some DPMI hosts and VCPI/XMS/raw will not require the state to be saved, indicating this by returning a buffer size of zero in AX. In such cases, that addresses returned by this function can still be called, although the will simply return without performing any useful function.

Clients do not need to call the state save/restore procedures before using INT 31h function 0300h, 0301h, or 0302h. The state save/restore procedures are provided for clients that use the raw mode switch services only.


Function 0306 - Get Raw Mode Switch Addresses
Function 0306 Get Raw Mode Switch Addresses

PMODE/W API

Returns addresses that can be called for low level mode switching.

In:

  AX     = 0306h

Out:

  always successful:

    carry flag clear

    BX:CX  = segment:offset of real to protected mode switch procedure

    SI:EDI = selector:offset of protected to real mode switch procedure

Notes:

The real mode segment:offset returned by this function should be called only in real mode to switch to protected mode. The protected mode selector:offset returned by this function should be called only in protected mode to switch to real mode.

The mode switch procedures are entered by a FAR JMP to the appropriate address with the following parameters:

  AX    = new DS

  CX    = new ES

  DX    = new SS

  (E)BX = new (E)SP

  SI    = new CS

  (E)DI = new (E)IP

The processor is placed into the desired mode, and the DS, ES, SS, (E)SP, CS, and (E)IP registers are updated with the specific values. In other words, execution of the client continues in the requested mode at the address provided in registers SI:(E)DI. The values specified to be placed into the segment registers must be appropriate for the destination mode. That is, segment addresses for real mode, and selectors for protected mode.

The values in EAX, EBX, ECX, EDX, ESI, and EDI after the mode switch are undefined. EBP will be preserved across the mode switch call so it can be used as a pointer. FS and GS will contain zero after the mode switch.

If interrupts are disabled when the mode switch procedure is invoked, they will not be re-enabled by the host (even temporarily). It is up to the client to save and restore the state of the task when

using this function to switch modes. This requires the state save/restore procedures whose addresses can be obtained with INT 31h function 0305h.


Function 0400 - Get Version
Function 0400 Get Version

PMODE/W API

Returns the version of the DPMI Specification implemented by the DPMI host. The client can use this information to determine what functions are available.

In:

  AX     = 0400h

Out:

  always successful:

    carry flag clear

    AH   = DPMI major version as a binary number (VCPI/XMS/raw returns 00h)

    AL   = DPMI minor version as a binary number (VCPI/XMS/raw returns 5ah)

    BX   = flags:

           Bits Significance

           0    0 = host is 16bit (PMODE/W never runs under one of these)

                1 = host is 32bit

           1    0 = CPU returned to V86 mode for reflected interrupts

                1 = CPU returned to real mode for reflected interrupts

           2    0 = virtual memory not supported

                1 = virtual memory supported

           3-15 reserved

    CL   = processor type:

           03h = 80386

           04h = 80486

           05h = 80586

           06h-ffh = reserved

     DH   = current value of master PIC base interrupt (low 8 IRQs)

     DL   = current value of slave PIC base interrupt (high 8 IRQs)

Notes:

The major and minor version numbers are binary, not BCD. So a DPMI 0.9 implementation would return AH as 0 and AL as 5ah (90).


Function 0500 - Get Free Memory Information
Function 0500 Get Free Memory Information

PMODE/W API

Returns information about the amount of available memory. Since DPMI clients could be running in a multitasking environment, the information returned by this function should be considered advisory.

In:

  AX     = 0500h

  ES:EDI = selector:offset of 48 byte buffer

Out:

  if successful:

    carry flag clear

    buffer is filled with the following information:

      Offset  Length  Contents

      00h     4       Largest available free block in bytes

      04h     2ch     Other fields only supplied by DPMI

  if failed:

    carry flag set

Notes:

Only the first field of the structure is guaranteed to contain a valid value. Any fields that are not supported by the host will be set to -1 (0ffffffffh) to indicate that the information is not available.


Function 0501 - Allocate Memory Block
Function 0501 Allocate Memory Block

PMODE/W API

Allocates a block of extended memory.

In:

  AX     = 0501h

  BX:CX  = size of block in bytes (must be non-zero)

Out:

  if successful:

    carry flag clear

    BX:CX  = linear address of allocated memory block

    SI:DI  = memory block handle (used to resize and free block)

  if failed:

    carry flag set

Notes:

The allocated block is guaranteed to have at least DWORD alignment.

This function does not allocate any descriptors for the memory block. It is  the responsibility of the client to allocate and initialize any descriptors needed to access the memory with additional function calls.


Function 0502 - Free Memory Block
Function 0502 Free Memory Block

PMODE/W API

Frees a memory block previously allocated with the Allocate Memory Block function (0501h).

In:

  AX     = 0502h

  SI:DI  = memory block handle

Out:

  if successful:

    carry flag clear

  if failed:

    carry flag set

Notes:

No descriptors are freed by this call. It is the client's responsibility to free any descriptors that it previously allocated to map the memory block. Descriptors should be freed before memory blocks.


Function 0503 - Resize Memory Block
Function 0503 Resize Memory Block

PMODE/W API

Changes the size of a memory block previously allocated with the Allocate Memory Block function (0501h).

In:

  AX     = 0503h

  BX:CX  = new size of block in bytes (must be non-zero)

  SI:DI  = memory block handle

Out:

  if successful:

    carry flag clear

    BX:CX  = new linear address of memory block

    SI:DI  = new memory block handle

  if failed:

    carry flag set

Notes:

After this function returns successfully, the previous handle for the memo block is invalid and should not be used anymore.

It is the client's responsibility to update any descriptors that map the memory block with the new linear address after resizing the block.


Function 0800 - Physical Address Mapping
Function 0800 Physical Address Mapping

PMODE/W API

Converts a physical address into a linear address. This functions allows the client to access devices mapped at a specific physical memory address.

In:

  AX     = 0800h

  BX:CX  = physical address of memory

  SI:DI  = size of region to map in bytes

Out:

  if successful:

    carry flag clear

    BX:CX  = linear address that can be used to access the physical memory

  if failed:

    carry flag set

Notes:

It is the caller's responsibility to allocate and initialize a descriptor for access to the memory.

Clients should not use this function to access memory below the 1 MB boundary.


Function 0801 - Free Physical Address Mapping
Function 0801 Free Physical Address Mapping

PMODE/W API

Releases a mapping of physical to linear addresses that was previously obtained with function 0800h.

In:

  AX     = 0801h

  BX:CX  = linear address returned by physical address mapping call

Out:

  if successful:

    carry flag clear

  if failed:

    carry flag set

Notes:

The client should call this function when it is finished using a device previously mapped to linear addresses with function 0801h.


Function 0900 - Get and Disable Virtual Interrupt State
Function 0900 Get and Disable Virtual Interrupt State

PMODE/W API

Disables the virtual interrupt flag and returns the previous state of it.

In:

  AX     = 0900h

Out:

  always successful:

    carry flag clear

    AL     = 0 if virtual interrupts were previously disabled

    AL     = 1 if virtual interrupts were previously enabled

Notes:

AH is not changed by this function. Therefore the previous state can be restored by simply executing another INT 31h.

A client that does not need to know the prior interrupt state can execute the CLI instruction rather than calling this function. The instruction may be trapped by a DPMI host and should be assumed to be very slow.


Function 0901 - Get and Enable Virtual Interrupt State
Function 0901 Get and Enable Virtual Interrupt State

PMODE/W API

Enables the virtual interrupt flag and returns the previous state of it.

In:

  AX     = 0901h

Out:

  always successful:

    carry flag clear

    AL     = 0 if virtual interrupts were previously disabled

    AL     = 1 if virtual interrupts were previously enabled

Notes:

AH is not changed by this function. Therefore the previous state can be restored by simply executing another INT 31h.

A client that does not need to know the prior interrupt state can execute the STI instruction rather than calling this function. The instruction may be trapped by a DPMI host and should be assumed to be very slow.


Function 0902 - Get Virtual Interrupt State
Function 0902 Get Virtual Interrupt State

PMODE/W API

Returns the current state of the virtual interrupt flag.

In:

  AX     = 0902h

Out:

  always successful:

    carry flag clear

    AL     = 0 if virtual interrupts are disabled

    AL     = 1 if virtual interrupts are enabled

Notes:

This function should be used in preference to the PUSHF instruction to examine the interrupt flag, because the PUSHF instruction returns the physical interrupt flag rather than the virtualized interrupt flag. On some DPMI hosts, the physical interrupt flag will always be enabled, even when the hardware interrupts are not being passed through to the client.


Function EEFF - Get DOS Extender Information
Function EEFF Get DOS Extender Information

PMODE/W API

Returns information about the DOS extender.

In:

  AX     = EEFFh

Out:

  if successful:

    carry flag clear

    EAX    = 'PMDW' (504D4457h)

    ES:EBX = selector:offset of ASCIIZ copyright string

    CH     = protected mode system type (0=raw, 1=XMS, 2=VCPI, 3=DPMI)

    CL     = processor type (3=386, 4=486, 5=586)

    DH     = extender MAJOR version (binary)

    DL     = extender MINOR version (binary)

  if failed:

    carry flag set

Notes:

In PMODE/W's implementation of this function, the value returned in ES is equivalent to the 4G data selector returned in DS at startup.

This function is always successful under PMODE/W.


What's New

Compiler changes

•	All known bugs have been fixed.

•	The quality of the generated code has been improved.

•	True floating-point calling conventions have been implemented. The Single, Double and Extended type arguments are passed to a function/procedure by value, but not by reference as in previous versions of the compiler. However it's still possible to use the old-style conventions by means of the arg_no_fp_on_stack calling convention specifier.

•	The reserved word packed has been added.

•	The reserved word out has been added.

•	The "-uses" command-line compiler directive has been added. It allows inclusion of additional RTL units in the application.

•	By default the procedural types now are 32-bit sized (see arg_proc_based for details).

•	The Integer type has been changed to 32-bit.

•	The Real type has been changed to 64-bit.

•	New ByteBool, WordBool, LongBool and Real48.

•	A possibility to define special writing and printing procedures for any custom type was added (see __reader and __writer for details).

RTL changes

•	All known bugs have been fixed.

•	Following procedures and functions have been added to the System unit:

         CompareMem

         QSort

         SwapArgs

•	The following units have been added:

         CompMath

         Use16

IDE for Windows (IDEW32)

•	Many improvements have been made.


Contacting TMT Development Corporation

Email:	support@tmt.com

sales@tmt.com

Web:	http://www.tmt.com

Tel:	1 631 689 3172

1-888-456-1105 (from North America only)

Mail:	TMT Development Corp

19 POPLAR AVE,

Stony Brook, NY 11790-1751