File:  [Coherent Logic Development] / freem / doc / freem.texi
Revision 1.11: download - view: text, annotated - select for diffs
Sat Mar 29 16:50:42 2025 UTC (3 days, 7 hours ago) by snw
Branches: MAIN
CVS tags: HEAD
Back to cvs-current as version for development; temp fix for double-free issue in global_dispatch

\input texinfo
@paragraphindent 0
@setfilename freem.info
@settitle The FreeM Manual

@copying
This manual is for FreeM, (version cvs-current), which is a free and open-source implementation of the M programming language.


Copyright @copyright{} 2014-2025 Coherent Logic Development LLC

@quotation
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover texts, and with no Back-Cover Texts.
@end quotation
@end copying

@titlepage

@title The FreeM Manual
@subtitle @sc{The Official Manual of FreeM}
@subtitle Version cvs-current
@c@vskip 10pt
@c@center @image{freem-logo-sm,,,,.png}
@author Serena Willis
@page
@vskip 0pt plus 1filll
@insertcopying
@end titlepage
@contents

@ifnottex
@node Top
@top The FreeM Manual

This is the official manual for the FreeM programming language.
@end ifnottex

@dircategory The FreeM Manual
@direntry
* FreeM: (freem).                       The FreeM M programming language.
@end direntry

@menu
* Introduction::                        About the FreeM Project, its history, and its goals.
* FreeM Invocation::                    How to invoke FreeM from the command line.
* The FreeM Daemon::                    Managing shared resources in the FreeM environment.
* The FreeM Direct-Mode Environment::   Executing M programs interactively.

* Directives::                          Per-Routine Language Directives.
* Intrinsic Special Variables::         Intrinsic Special Variables.
* Intrinsic Functions::                 Intrinsic Functions.
* OBJECT Methods::                      Methods for OBJECT variables.
* STRING Methods::                      Methods for STRING variables.
* Commands::                            Commands.
* Structured System Variables::         Structured System Variables.
* Operators::                           FreeM Operators.

* Routines::                            The units of M code in FreeM.
* Types::                               FreeM data types.
* Globals::                             FreeM persistent sparse arrays.
* Concurrency Control::                 @code{LOCK}ing and transaction processing.
* Local Variables::                     In-memory variables.
* Scoping::                             Scoping in FreeM.
* Decision Constructs::                 @code{IF}, @code{THEN}, @code{ELSE}, @code{$SELECT}, and postconditionals.
* Branch Constructs::                   Labels, @code{GOTO}, @code{DO}, and @code{JOB}.
* Loop Constructs::                     The @code{FOR} loop.
* Modular Programming::                 Extrinsic functions and subroutines.
* Object-Oriented Programming::         Classes and objects in FreeM.
* Libraries::                           System and user libraries.
* Sequential I/O::                      Processing sequential files in FreeM.
* Network I/O::                         Handling network sockets in FreeM.
* Extended Global References::          Accessing globals in non-default namespaces.
* Global Aliasing::                     Defining alternate names for globals.
* Global Mappings::                     Mapping global names to non-default namespaces.

* Transaction Processing::              Transactions in FreeM.
* Asynchronous Event Handling::         Handling asynchronous events in FreeM.
* Global Triggers::                     Responding to global accesses in M code.
* Synchronous Event Handling::          Synchronous events in FreeM.


* GUI Programming with MWAPI::          Creating graphical interfaces in FreeM.

* User-Defined Z Commands::             Adding your own Z commands to FreeM.
* User-Defined Z Functions::            Adding your own Z functions to FreeM.
* User-Defined SSVNs::                  Adding your own SSVNs to FreeM.

* Language Dialects::                   Controlling FreeM standards compliance.

* System Library Routines::             FreeM built-in library of M routines.

* Interrupt Handling::                  How FreeM handles interrupts.
* Error Processing::                    How to handle errors in M program code.
* FreeM Error Codes::                   Explanations of each FreeM error code.
* Debugging::                           The program development cycle of FreeM.

* System Configuration::                Configuring your FreeM installation.
* Accessing FreeM from C Programs::     How to use the mlib interface.

* FreeM Administrator::                 The fmadm system manager tool.
* FreeM Legacy Utilities::              FreeM legacy system manager utilities.
* FreeM VIEW Commands and Functions::   Getting and setting info about FreeM internals.
* Implementation Limits::               FreeM limitations.
* US-ASCII Character Set::              The US-ASCII character set.
* FreeM Project Coding Standards::      How to write code for submission to the FreeM project.

* Index::               Complete index.
@end menu

@node Introduction
@unnumbered Introduction


FreeM started its life as @emph{FreeMUMPS}, written for MS-DOS and ported to SCO UNIX by a mysterious individual going by the name of "Shalom ha-Ashkenaz". It was released to MUG Deutschland in 1998. In 1999, Ronald L. Fox ported FreeM to the Red Hat Linux 5 of the GNU/Linux operating system. Thereafter, maintenance was taken over by the Generic Universal M Project, which changed its name first to Public Standard MUMPS and then by popular request to FreeM.

When GT.M was open-sourced in late 1999, FreeM and GUMP were essentially abandoned. L.D. Landis, the owner of the original GUMP SourceForge project, and one of FreeM's significant contributors, passed maintenance of FreeM and ownership of its SourceForge project to Serena Willis in 2014. At this point, FreeM would not compile or run on modern Linux systems, so steps were taken to remedy the most pressing issues in the codebase. Limitations on the terminal size (previously hard-coded to 80x25) were lifted, and new @code{$VIEW} functions were added to retrieve the terminal size information. @code{$X} and @code{$Y} intrinsic special variables were updated to support arbitrary terminal sizes, and FreeM was once again able to build and run.

In February of 2020, work began in earnest to build a development and support infrastructure for FreeM and begin the careful process of refining it into a more stable and robust product.

@section Production Readiness

FreeM is not yet production-ready. There are several show-stopping bugs that preclude a general release for public use:

@itemize @bullet

@item
@code{@ref{VIEW}} commands and @code{@ref{$VIEW()}} functions are used extensively to configure and inspect the run-time behavior of FreeM, rather than the "canonical" SSVN-based approach.

@item
Server sockets are not yet implemented.

@item
There are some situations that can result in segmentation faults and/or lock-ups.

@item
In spite of our best efforts, this manual is not yet complete.

@end itemize

@section Contributors
Current contributors denoted with a @emph{+} following their name and role.
@cindex contributors, ha-Ashkenaz, Shalom
@cindex contributors, Best, John
@cindex contributors, Diamond, Jon
@cindex contributors, Fox, Ronald L.
@cindex contributors, Gerum, Winfried
@cindex contributors, Kreis, Greg
@cindex contributors, Landis, Larry
@cindex contributors, Milligan, Lloyd
@cindex contributors, Morris, Steve
@cindex contributors, Murray, John
@cindex contributors, Pastoors, Wilhelm
@cindex contributors, Schell, Kate
@cindex contributors, Schofield, Lyle
@cindex contributors, Stefanik, Jim
@cindex contributors, Trocha, Axel
@cindex contributors, Walters, Dick
@cindex contributors, Whitten, David
@cindex contributors, Wicksell, David
@cindex contributors, Willis, Serena
@cindex contributors, Zeck, Steve

@itemize @bullet

@item
Shalom ha-Ashkenaz (Original Implementer)

@item
John Best (IBM i and OS/400)

@item
Jon Diamond (Library, Utilities, Conformance)

@item
Ronald L. Fox (Initial port to Red Hat 5/libc-6)

@item
Winfried Gerum (Code, Advice, MTA coordination)

@item
Greg Kreis (Hardhats coordination, Dependencies)

@item
Larry Landis (Coordination, Code, Documentation)

@item
Rick Marshall (Testing, MDC Conformance) @emph{+}

@item
Lloyd Milligan (Code, Testing, Documentation)

@item
Steve Morris (Code, Microsoft)

@item
John Murray (Code, Conformance)

@item
Wilhelm Pastoors (Testing, Documentation)

@item
Kate Schell (Coordination, Conformance, MTA, MDC, Advice)

@item
Lyle Schofield (Advice, Prioritization, Tracking, Project Management)

@item
Jim Stefanik (GNU/Linux on s390x, IBM AIX, IBM z/OS)

@item
Axel Trocha (Code, Utilities)

@item
Dick Walters (Project Lead, Chief Coordinator, MTA)

@item
David Whitten (QA Test Suite, MDC, Advice) @emph{+}

@item
David Wicksell (Debugging, Code, Testing) @emph{+}

@item
Serena Willis (Current Maintainer and Project Lead) @emph{+}

@item
Steve Zeck (Code)

@end itemize
@node FreeM Invocation
@chapter FreeM Invocation
@cindex invocation, command-line
@cindex options, command-line

@section Synopsis
@example
$ @command{./freem} [@emph{OPTIONS}...] [[-r <entryref>] | [--routine=<entryref>]]
@end example

When FreeM loads, it searches the @code{SYSTEM} namespace for the @code{^%SYSINIT} routine, and begins executing it.

When @code{-r} or @code{--routine} are passed on the command line, FreeM will load and run the specified routine instead of @code{^%SYSINIT}. Beginning with FreeM 0.1.7, routines invoked in this manner are no longer required to perform their own namespace setup with @code{VIEW} commands. 

@section Command-Line Options

@table @asis

@item @option{-d}, @option{--daemon}
Starts the FreeM daemon, exactly one of which must be running at all times in order for FreeM interpreter and fmadm processes to function.

@item @option{-e}, @option{--environment}
Selects the environment to be used. If no environment is specified, @code{DEFAULT} is used.

@item @option{-k}, @option{--nofork}
When used with @option{-d} or @option{--daemon}, causes the FreeM daemon to run instead in the foreground. Useful for debugging.

@item @option{-p}, @option{--pidfile}
When used with @option{-d} or @option{--daemon}, sets the file in which the PID of the running daemon is stored.

@item @option{-S}, @option{--shmsize}
When used with @option{-d} or @option{--daemon}, specifies the number of bytes of shared memory FreeM will allocate for the @code{LOCK} table, job table, and IPC table. This will determine the maximum number of concurrent FreeM processes and @code{LOCK}s available in this environment. 

@item @option{-c}, @option{--config}
Specify a configuration file other than @code{$PREFIX/etc/freem.conf}.

@item @option{-h}, @option{--help}
Display a help message showing valid FreeM options.

@item @option{-i}, @option{--import}
Causes your UNIX environment variables to be imported into FreeM's local symbol table.

@item @option{-f}, @option{--filter}
Allows your M routines to be used as UNIX filters.

@item @option{-n @emph{<namespace-name>}}, @option{--namespace=@emph{<namespace-name>}}
Selects the FreeM namespace to be entered on startup. Must be defined in @file{/etc/freem.conf}.

@item @option{-r @emph{<entryref>}}, @option{--routine=@emph{<entryref>}}
Causes @code{<entryref>} to be executed at load, instead of @code{^%SYSINIT}.

@item @option{--standard=@emph{<standard>}}
Sets the default FreeM dialect to use for new routine buffers.

Valid values for @code{@emph{<standard>}} are as follows:

@table @code
@item @code{M77}
Restricts FreeM to use only features specified by the 1977 M standard.
@item @code{M84}
Restricts FreeM to use only features specified by the 1984 M standard.
@item @code{M90}
Restricts FreeM to use only features specified by the 1990 M standard.
@item @code{M95}
Restricts FreeM to use only features specified by the 1995 M standard.
@item @code{MDS}
Restricts FreeM to use only features proposed by the Millennium Draft Standard.
@item @code{M5}
Restricts FreeM to use only features proposed by the upcoming M5 standard.
@item @code{FREEM}, @code{EXTENDED}
Removes all standards-based restrictions and allows full access to all FreeM features. This is the default value of @code{$DIALECT}.
@end table

Please note that FreeM is not entirely standards-compliant, regardless of the value of @code{@emph{<standard>}}.

@item @option{-v}, @option{--version}
Displays FreeM version information.

@item @option{-x @emph{<mcode>}}, @option{--execute=@emph{<mcode>}}
Executes M code @code{<mcode>} at startup instead of the startup routine.

@end table

@section Using FreeM for Shell Scripting
@cindex routines, as shell scripts
@cindex shebang line
@cindex shell scripting

FreeM M routines can be used as shell scripts by providing a @emph{shebang} line beginning with @code{#!/path/to/freem} as the first line of the routine.
The following example presumes that FreeM is installed at @file{/usr/local/bin/freem} and uses the @code{USER} namespace:

@example
#!/usr/local/bin/freem
MYSCRIPT ;
 SET ^$JOB($JOB,"NAMESPACE")="USER"
 WRITE "This is output from an M routine used as a shell script.",!
 Q
@end example

Currently, the script needs to have a @file{.m} file extension. You will also need to select an appropriate namespace in your script using the @code{SET ^$JOB($JOB,"NAMESPACE")="@emph{<namespace>}"} command before attempting to call other routines or access globals.

You will also need to set the script's permissions to @emph{executable} in order for this to work:

@example
$ chmod +x @emph{myscript.m}
@end example

@node The FreeM Daemon
@chapter The FreeM Daemon
@cindex daemon, freem

The FreeM daemon manages shared resources for a given FreeM environment. These include the lock table, job table, inter-process communication, and concurrency control for transaction processing. Unlike some M implementations, the FreeM daemon does @emph{not} function as a write daemon for global storage.

One daemon process is required per FreeM environment, and can be started as follows:

@example
$ freem --daemon [--nofork] [--environment=<environment-name>] [--user=<username>] \
        [--group=<group-name>] [--pidfile=<pid-file>] [--shmsize=<bytes>]
@end example

If the daemon is started with @option{--nofork}, it will run in the foreground and its output will be reflected on the terminal. Otherwise, the daemon will run as a child process in the background and immediately return terminal control to the shell. The latter option is recommended in most cases.

The @option{--environment} option will start the daemon for the specified @emph{environment-name}. The default environment, if unspecified, is called @code{DEFAULT}. If using an environment other than @code{DEFAULT}, interpreter processes that wish to also connect to the same environment must also use the @option{--environment} option when starting, and @code{libfreem} clients must also pass the environment name as the first argument to the @code{freem_init()} function. Environments allow you to run multiple, isolated instances of FreeM on the same machine, whose globals and routines are distinct and unique.

The @option{--user} and @option{--group} options are only valid when the FreeM daemon is started by the superuser, and will cause the daemon to reduce its runtime privileges to those of the specified user and group, and run as that user and/or group. We recommend creating a @code{freem} user and group and running the FreeM daemon with @code{--user=freem --group=freem}.

The @option{--pidfile} option specifies the file in which the FreeM daemon will store its own PID. If running as the superuser, the FreeM daemon will store the PID file in @code{/var/run/freem.pid}. Otherwise, the PID file will be stored as @code{.freem.pid} in the home directory of the user account which owns the FreeM daemon process.

The @option{--shmsize} option specifies the size in bytes of the FreeM shared memory segment. The default is 4194304 bytes. Increasing the size of the FreeM shared memory segment will, at the cost of increased memory usage, increase the number of concurrent jobs and lock table entries available to the environment; decreasing the size of the segment will have the expected opposite effect. Note that you must also pass @option{--shmsize} with the same number of bytes to any interpreter process to be used with an environment whose daemon uses a non-default shared memory segment size.

Attempting to start a FreeM interpreter process without a daemon running with the same environment name will result in an error.

@node The FreeM Direct-Mode Environment
@chapter The FreeM Direct-Mode Environment
@cindex command line interface
@cindex direct mode
@cindex execution, interactive
@cindex modes, programmer


The FreeM direct-mode environment is the mode entered when FreeM is invoked without the use of @option{-r @emph{<entryref>}} or @option{--routine=@emph{<entryref>}}:

@example
Coherent Logic Development FreeM version cvs-current (x86_64-pc-linux-gnu)
Copyright (C) 2014, 2020, 2021 Coherent Logic Development LLC


USER>
@end example

The prompt (@code{USER>}) indicates the currently-active namespace. If any uncommitted direct-mode transactions have been started, the prompt will change to reflect the current value of @code{@ref{$TLEVEL}}:

@example
TL1:USER>
@end example

In the above example, @code{TL1} indicates that @code{@ref{$TLEVEL}} is currently @emph{1}.

@section Direct-Mode Commands

When you are in direct mode, in addition to M commands, a number of internal commands are available to help developers be more productive:

@table @asis

@item @command{?}
Accesses FreeM online help. Requires GNU @command{info(1)} to be installed on your local system.

@item @command{events}
Writes a list of @emph{event classes} and their @code{ABLOCK} counts:

@example
USER> events
 
Event Class          Processing Mode ABLOCK Count
-----------          --------------- ------------
COMM                 Disabled        0
HALT                 Disabled        0
IPC                  Disabled        0
INTERRUPT            Disabled        0
POWER                Disabled        0
TIMER                Disabled        0
USER                 Disabled        0
WAPI                 Disabled        0
TRIGGER              Disabled        0
@end example


@anchor{trantab}
@item @command{trantab}
Displays information about any uncommitted transactions currently in-flight for this process.

@anchor{jobtab}
@item @command{jobtab}
Displays a summary of the FreeM job table.

@anchor{locktab}
@item @command{locktab}
Displays a list of @code{LOCK}s held in the current environment.

@anchor{rbuf}
@item @command{rbuf}
Lists the status of all FreeM routine buffers.

@anchor{dbstats}
@item @command{dbstats}
Shows statistics for the BerkeleyDB global handler.

@anchor{wh}
@item @command{wh}
Forces an immediate flush of this process's @code{readline} history buffer to disk.

@anchor{shmstat}
@item @command{shmstat}
Displays the configuration of FreeM shared memory. Intended only for advanced debugging of the FreeM environment.

@anchor{shmpages}
@item @command{shmpages}
Lists the status of each FreeM shared memory page. Intended only for advanced debugging of the FreeM environment.

@anchor{history}
@item @command{history}
Prints a list of all the direct-mode commands you have entered across all sessions.

@anchor{rcl}
@item @command{rcl @emph{<history-index>}}
Allows you to recall command number @emph{<history-index>} and run it again. Obtain the value for @emph{<history-index>} from the output of the @command{history} command.

@item @command{!!}
Launches a subshell within the FreeM direct mode, allowing the user to run operating system commands.

@example
USER> !!

Type Ctrl-D to exit from the shell
$ uname -a
Linux hesperos 4.19.0-17-amd64 #1 SMP Debian 4.19.194-3 (2021-07-18) x86_64 GNU/Linux
$ exit

USER> 
@end example

@item @command{!@emph{<external-command>}}
Invokes a shell to run @emph{<external-command>} from within FreeM. This temporarily disables @command{SIGALRM} handling in FreeM, which may interrupt the use of event-driven M programming commands including @command{ESTART} and @command{ESTOP}.

If the @command{>} character is supplied immediately preceding @emph{<external-command>}, FreeM will append the contents of an M local or global variable referenced in @code{^$JOB($JOB,"PIPE_GLVN")} to the standard input stream of @emph{<external-command>}.

If the @command{<} character is supplied immediately preceding @emph{<external-command>}, FreeM will take the standard output stream of @emph{<external-command>} and store it in M local or global variable referenced by @code{^$JOB($JOB,"PIPE_GLVN")}.

The data value in the unsubscripted M local or global contains the number of lines in the input or output. Subscripts @code{(1)..(@emph{n})} contain the data for lines 1-@emph{n}.

@end table

@cindex HALT, in direct-mode
If you issue a @code{@ref{HALT}} command at the direct-mode prompt, you will exit out of FreeM. However, if you issue a @code{@ref{HALT}} command when @code{@ref{$TLEVEL}} is greater than zero, you will be given the opportunity to commit or rollback any pending transactions:

@example
USER> TSTART
 

TL1:USER> SET ^MYGLOBAL=1
 
 
TL1:USER> HALT
 
UNCOMMITTED TRANSACTIONS EXIST:
 
 $TLEVEL 1*
  Operations for Transaction ID: k8xj1de
  1:	action = 0  key = ^MYGLOBAL  data = 1
 
Would you like to c)ommit or r)ollback the above transactions and their operations? ($TLEVEL = 1) r


Transactions have been rolled back.
@end example

In the above example, the user selected @code{r} to rollback the single pending transaction.

@section REPL Functionality
@cindex REPL, direct-mode

FreeM direct mode allows you to enter M expressions directly from the direct-mode prompt, as long as they begin with a number:

@example
USER> S DENOM=10
 
 
USER> 100/DENOM
 
10
USER> 
@end example

Such expressions will be immediately evaluated, and the result printed on @code{@ref{$IO}}.

@node Directives
@chapter Directives
@cindex directives

In FreeM, a directive is an instruction embedded in an M comment, and passed to the interpreter to affect a change that is specific to the current routine only.

The format of a directive is @code{;%@emph{<directive-name>}}, where @code{@emph{<directive-name>}} is one of the directives listed below.

@menu
* %DIALECT::            Sets the M dialect in effect.
@end menu

@anchor{%DIALECT}
@section %DIALECT
@cindex %DIALECT
@cindex directives, %DIALECT

Sets the M dialect in effect for the current routine buffer; also sets the @code{$DIALECT} special variable to match. See also @ref{$DIALECT}.

@emph{Syntax}

@example
;%DIALECT @emph{<dialect>}
@end example

Valid values for @code{@emph{<dialect>}} are as follows:

@table @code
@item @code{M77}
Restricts FreeM to use only features specified by the 1977 M standard.
@item @code{M84}
Restricts FreeM to use only features specified by the 1984 M standard.
@item @code{M90}
Restricts FreeM to use only features specified by the 1990 M standard.
@item @code{M95}
Restricts FreeM to use only features specified by the 1995 M standard.
@item @code{MDS}
Restricts FreeM to use only features proposed by the Millennium Draft Standard.
@item @code{M5}
Restricts FreeM to use only features proposed by the upcoming M5 standard.
@item @code{FREEM}, @code{EXTENDED}
Removes all standards-based restrictions and allows full access to all FreeM features. This is the default value of @code{%DIALECT}.
@end table

Please note that FreeM is not entirely standards-compliant, regardless of the value of @code{%DIALECT}.


@node Intrinsic Special Variables
@chapter Intrinsic Special Variables
@cindex variables, intrinsic special

@menu
* $DEVICE::                  $IO device status.
* $DIALECT::                 Current M dialect.
* $ECODE::                   Latest M error code.
* $ESTACK::                  Error stack info.
* $ETRAP::                   Standard error handler code.
* $HOROLOG::                 Current date and time.
* $IO::                      Current I/O device.
* $JOB::                     PID of current process.
* $KEY::                     Characters terminating last @code{READ} command.
* $PDISPLAY::                Current primary MWAPI display.
* $PRINCIPAL::               I/O channel of terminal.
* $REFERENCE::               Most recent global reference.
* $QUIT::                    Whether a @code{QUIT} command requires an argument in the current execution context.
* $STACK::                   Current program execution stack level.
* $STORAGE::                 Number of bytes available in the heap.
* $SYSTEM::                  MDC system ID of FreeM.
* $TEST::                    Truth value of last conditional expression or result of certain @code{LOCK} operations.
* $TLEVEL::                  Current level of transaction nesting.
* $WITH::                    Current variable prefix set by @code{WITH} command.
* $X::                       Current horizontal screen position.
* $Y::                       Current vertical screen position.
* $ZA::                      Current position of file on @code{$IO}.
* $ZB::                      Most recent keystroke.
* $ZCONTROLC::               Control-C handling flag.
* $ZDATE::                   Current date in locale-specific representation.
* $ZERROR::                  Last error message.
* $ZHOROLOG::                Date and time, including milliseconds.
* $ZINRPT::                  State of the interrupt enable/disable flag.
* $ZJOB::                    PID of parent process, if applicable.
* $ZLOCAL::                  Last local variable reference.
* $ZNAME::                   Name of current M routine.
* $ZPRECISION::              Digits of arithmetical precision.
* $ZREFERENCE::              Last gvn referenced.
* $ZSYSTEM::                 Return value of last external command.
* $ZTIME::                   Current time in locale-specific representation.
* $ZTRAP::                   Entryref to be executed on error condition.
* $ZUT::                     Microseconds since the UNIX epoch.
* $ZVERSION::                Version of FreeM and GNU host triplet.
@end menu 

@node $DEVICE
@section $DEVICE
@cindex $DEVICE
@cindex intrinsic special variables, $DEVICE

Returns the status of the device currently in use.

If @code{$DEVICE} returns @emph{1}, an error condition exists on the current device. In this case, there will be two additional fields separated by commas, indicating the internal FreeM error code representing the error present on the device and a text explanation of the error.

@node $DIALECT
@section $DIALECT
@cindex $DIALECT
@cindex intrinsic special variables, $DIALECT

Returns or sets the language dialect of the current routine.

Valid values for @code{$DIALECT} are as follows:

@table @code
@item @code{M77}
Restricts FreeM to use only features specified by the 1977 M standard.
@item @code{M84}
Restricts FreeM to use only features specified by the 1984 M standard.
@item @code{M90}
Restricts FreeM to use only features specified by the 1990 M standard.
@item @code{M95}
Restricts FreeM to use only features specified by the 1995 M standard.
@item @code{MDS}
Restricts FreeM to use only features proposed by the Millennium Draft Standard.
@item @code{M5}
Restricts FreeM to use only features proposed by the upcoming M5 standard.
@item @code{FREEM}, @code{EXTENDED}
Removes all standards-based restrictions and allows full access to all FreeM features. This is the default value of @code{$DIALECT}.
@end table

Please note that FreeM is not entirely standards-compliant, regardless of the value of @code{$DIALECT}.

@node $ECODE
@section $ECODE
@cindex $ECODE
@cindex intrinsic special variables, $ECODE

Returns a comma-delimited list of error conditions currently present, and is writable. An empty @code{$ECODE} indicates no errors.

@node $ESTACK
@section $ESTACK
@cindex $ESTACK
@cindex intrinsic special variables, $ESTACK

Returns the depth of the program execution stack since the last time @code{$ESTACK} was @code{NEW}ed. @code{NEW}-able, but not @code{SET}-able. Differs from the @code{@ref{$STACK}} ISV in that it is @code{@ref{NEW}}-able, and resets to a value of 0 when @code{@ref{NEW}}ed.

@node $ETRAP
@section $ETRAP
@cindex $ETRAP
@cindex intrinsic special variables, $ETRAP

Sets or retrieves the M code that is run when an error is encountered or @code{@ref{$ECODE}} is set to a non-blank value. @code{$ETRAP} code executes when @code{$ECODE} becomes non-blank.


@node $HOROLOG
@section $HOROLOG
@cindex $HOROLOG
@cindex intrinsic special variables, $HOROLOG

Returns a string containing the current date and time as @code{<days>,<seconds>}, where @code{<days>} represents the number of days since the M epoch (midnight on 31 December 1840),
and @code{<seconds>} represents the number of seconds since the most recent midnight.

@cartouche
@quotation
@emph{FreeM Extension}

In FreeM, @code{$HOROLOG} is @code{@ref{SET}}table. Setting @code{$HOROLOG} will set the system clock if your user account has the appropriate permissions. If your user account does not have permissions to modify the system clock, FreeM will raise a @code{ZPROTECT} error.
@end quotation
@end cartouche

@node $IO
@section $IO
@cindex $IO
@cindex intrinsic special variables, $IO

Represents the current input/output device. Read-only.

@node $JOB
@section $JOB
@cindex $JOB
@cindex intrinsic special variables, $JOB

Represents the process ID of the FreeM instance currently in use.

@node $KEY
@section $KEY
@cindex $KEY
@cindex intrinsic special variables, $KEY

Represents the sequence of control characters that terminated the last @code{@ref{READ}} command on @code{@ref{$IO}}.

@node $PDISPLAY
@section $PDISPLAY
@cindex $PDISPLAY
@cindex intrinsic special variables, $PDISPLAY

Represents the current principal display for M Windowing API operations. Commonly used as an index into the @code{@ref{^$DISPLAY}} structured system variable.

@node $PRINCIPAL
@section $PRINCIPAL
@cindex $PRINCIPAL
@cindex intrinsic special variables, $PRINCIPAL

Represents the primary input/output device. Usually a terminal or virtual terminal.

@node $REFERENCE
@section $REFERENCE
@cindex $REFERENCE
@cindex intrinsic special variables, $REFERENCE

Returns the last @emph{glvn} referenced. Can be @code{@ref{SET}}, and also stacked with @code{@ref{NEW}}.

@node $QUIT
@section $QUIT
@cindex $QUIT
@cindex intrinsic special variables, $QUIT

If the current execution context was invoked as an extrinsic function, @code{$QUIT} returns @emph{1}. Otherwise, returns @emph{0}.

When @code{$QUIT} returns @emph{1}, a subsequent @code{@ref{QUIT}} command must have an argument.

@node $STACK
@section $STACK
@cindex $STACK
@cindex intrinsic special variables, $STACK

Represents the current stack level.

@node $STORAGE
@section $STORAGE
@cindex $STORAGE
@cindex intrinsic special variables, $STORAGE

Represents the number of bytes of free space available in FreeM's heap.

@node $SYSTEM
@section $SYSTEM
@cindex $SYSTEM
@cindex intrinsic special variables, $SYSTEM

Returns the MDC system ID of FreeM, as well as the environment ID of the current environment.

@node $TEST
@section $TEST
@cindex $TEST
@cindex intrinsic special variables, $TEST

@code{$TEST} is a writable, @code{@ref{NEW}}-able ISV that is @emph{1} if the most recently evaluated expression was @emph{true}. Otherwise, returns @emph{0}.

@code{$TEST} is implicitly @code{NEW}ed when entering a new stack frame for extrinsic functions and argumentless @code{@ref{DO}}. @code{$TEST}
is @emph{not} implicitly @code{NEW}ed when a new stack frame is entered with an argumented @code{DO}.

For single-line @code{@ref{IF}} or @code{@ref{ELSE}} expressions, you may use @code{@ref{THEN}} to stack @code{$TEST} until the end of the line. All new code should employ @code{THEN} in this manner, as stacking @code{$TEST} prevents a wide range of coding errors that can be very challenging to detect and eliminate.

@node $TLEVEL
@section $TLEVEL
@cindex $TLEVEL
@cindex intrinsic special variables, $TLEVEL

Returns a numeric value indicating the current level of transaction nesting in the process. When @code{$TLEVEL} is greater than @emph{0},
uncommitted transactions exist.

@node $WITH
@section $WITH
@cindex $WITH
@cindex intrinsic special variables, $WITH

Returns the variable prefix set by the @code{@ref{WITH}} command.

@node $X
@section $X
@cindex $X
@cindex intrinsic special variables, $X

Represents the current column position of the FreeM cursor.

@cartouche
@quotation
In FreeM, setting @code{$X} will move the FreeM cursor.
@end quotation
@end cartouche


@node $Y
@section $Y
@cindex $Y
@cindex intrinsic special variables, $Y

Represents the current row position of the FreeM cursor.

@cartouche
@quotation
In FreeM, setting @code{$Y} will move the FreeM cursor.
@end quotation
@end cartouche


@node $ZA
@section $ZA
@cindex $ZA
@cindex intrinsic special variables, $ZA
@cindex intrinsic special variables, implementation-specific

On the @code{HOME} device, always @code{0}. On other devices, returns the current position of the file opened on I/O channel @code{@ref{$IO}}.

@node $ZB
@section $ZB
@cindex $ZB
@cindex intrinsic special variables, $ZB
@cindex intrinsic special variables, implementation-specific

Represents the last keystroke.

@node $ZCONTROLC
@section $ZCONTROLC
@cindex $ZCONTROLC
@cindex intrinsic special variables, $ZCONTROLC
@cindex intrinsic special variables, implementation-specific

Returns the status of the Ctrl-C flag and resets it to @emph{false}.

@node $ZDATE
@section $ZDATE
@cindex $ZDATE
@cindex intrinsic special variables, $ZDATE
@cindex intrinsic special variables, implementation-specific

Returns the current date, in the preferred representation for the current system locale.

@node $ZERROR
@section $ZERROR
@cindex $ZERROR
@cindex intrinsic special variables, $ZERROR
@cindex intrinsic special variables, implementation-specific

Returns the last error message.

@node $ZHOROLOG
@section $ZHOROLOG
@cindex $ZHOROLOG
@cindex intrinsic special variables, $ZHOROLOG
@cindex intrinsic special variables, implementation-specific

Output @code{@ref{$HOROLOG}}-style time, with the addition of milliseconds.

@node $ZINRPT
@section $ZINRPT
@cindex $ZINRPT
@cindex intrinsic special variables, $ZINRPT
@cindex intrinsic special variables, implementation-specific

Gets or sets the interrupt enable/disable flag.

@node $ZJOB
@section $ZJOB
@cindex $ZJOB
@cindex intrinsic special variables, $ZJOB
@cindex intrinsic special variables, implementation-specific

Returns the @code{@ref{$JOB}} value of the parent process if the current process was started by a @code{@ref{JOB}} command. Otherwise, returns an empty string.

@node $ZLOCAL
@section $ZLOCAL
@cindex $ZLOCAL
@cindex intrinsic special variables, $ZLOCAL
@cindex intrinsic special variables, implementation-specific

Returns the last local variable referenced.

@node $ZNAME
@section $ZNAME
@cindex $ZNAME
@cindex intrinsic special variables, $ZNAME
@cindex intrinsic special variables, implementation-specific

Returns the name of the current routine.

@node $ZPRECISION
@section $ZPRECISION
@cindex $ZPRECISION
@cindex intrinsic special variables, $ZPRECISION
@cindex intrinsic special variables, implementation-specific

Gets or sets the number of digits of numeric precision used for fixed-point decimal arithmetic. If @code{^$JOB($JOB,"MATH")} is @code{IEEE754}, @code{$ZPRECISION} defaults to 16 digits, with a maximum of 16 digits. If @code{^$JOB($JOB,"MATH")} is @code{FIXED}, @code{$ZPRECISION} defaults to 100 digits, with a maximum of 20,000 digits.

@xref{^$JOB}.

@node $ZREFERENCE
@section $ZREFERENCE
@cindex $ZREFERENCE
@cindex intrinsic special variables, $ZREFERENCE
@cindex intrinsic special variables, implementation-specific

Returns the last @emph{gvn} referenced.

@node $ZSYSTEM
@section $ZSYSTEM
@cindex $ZSYSTEM
@cindex intrinsic special variables, $ZSYSTEM
@cindex intrinsic special variables, implementation-specific

Represents the return value of the last external command run with @code{!}.

@node $ZTIME
@section $ZTIME
@cindex $ZTIME
@cindex intrinsic special variables, $ZTIME
@cindex intrinsic special variables, implementation-specific

Returns the system time in the preferred representation for the current system locale.

@node $ZTRAP
@section $ZTRAP
@cindex $ZTRAP
@cindex intrinsic special variables, $ZTRAP
@cindex intrinsic special variables, implementation-specific

Sets or retrieves the entryref to be executed when an M program execution error occurs under FreeM-style or DSM 2.0-style error processing.

In FreeM-style error processing, @code{$ZTRAP} is specific to each program execution stack level.

In DSM 2.0-style error processing, @code{$ZTRAP} is the same for all program execution stack levels.

When FreeM encounters an error, if @code{$ZTRAP} is nonempty and @code{$ETRAP} is empty, FreeM will perform an implicit @code{@ref{GOTO}} to the entryref indicated in @code{$ZTRAP}.

If @code{$ETRAP} is nonempty when FreeM encounters an error, the value of @code{$ZTRAP} is ignored, whether FreeM-style or DSM 2.0-style error processing is enabled.

@node $ZUT
@section $ZUT
@cindex $ZUT
@cindex intrinsic special variables, $ZUT
@cindex intrinsic special variables, implementation-specific

Returns the number of microseconds elapsed since the UNIX epoch (Jan 1, 1970 0:00:00).

@node $ZVERSION
@section $ZVERSION
@cindex $ZVERSION
@cindex intrinsic special variables, $ZVERSION
@cindex intrinsic special variables, implementation-specific

Returns the version of FreeM in use, as well as the GNU host triplet for the current FreeM build.

See @emph{https://wiki.osdev.org/Target_Triplet}.

@node Intrinsic Functions
@chapter Intrinsic Functions

@menu
* $ASCII()::                            Return ASCII code for character in string.
* $CHAR()::                             Return character for one or more ASCII codes.
* $DATA()::                             Retrieve definition and characteristics of array node.
* $EXTRACT()::                          Return a substring of a string.
* $FIND()::                             Find position of substring within string.
* $FNUMBER()::                          Format a number according to formatting codes.
* $GET()::                              Return value of glvn or a default if undefined.
* $INSTANCEOF()::                       Determine if lvn is an instance of a class.
* $JUSTIFY()::                          Right-justify a string based on specified length.
* $LENGTH()::                           Return length or delimiter-based piece count of string.
* $NAME()::                             Return canonical name from string representation of glvn.
* $NEXT()::                             Return next numeric subscript following given glvn.
* $ORDER()::                            Return next subscript at same level of specified glvn.
* $PIECE()::                            Return one or more delimited pieces of a string.
* $QLENGTH()::                          Return subscript count of glvn.
* $QSUBSCRIPT()::                       Return a specified subscript from glvn.
* $QUERY()::                            Return next subscript of specified glvn.
* $RANDOM()::                           Return pseudorandom integer up to a maximum value.
* $REVERSE()::                          Reverse a string.
* $SELECT()::                           Return value from first true condition in list of expressions.
* $STACK()::                            Return information about the program stack.
* $TEXT()::                             Return line of code from a routine.
* $TRANSLATE()::                        Substitute specified characters in a string.
* $TYPE()::                             Return class of the specified lvn.
* $VIEW()::                             Retrieve implementation-specific information.
* $ZBOOLEAN()::                         Perform boolean operations on numeric arguments.
* $ZCALL()::                            Unknown.
* $ZCRC()::                             Generate checksum of a string argument.
* $ZDATA()::                            Unknown.
* $ZDATE()::                            Convert @code{@ref{$HOROLOG}} string into human-readable date.
* $ZEDIT()::                            Unknown.
* $ZHOROLOG()::                         Convert date/time values to @code{@ref{$HOROLOG}} format.
* $ZKEY()::                             Unknown.
* $ZLENGTH()::                          Unknown.
* $ZLSD()::                             Compute Levenshtein distance between two arguments.
* $ZM()::                               Unknown.
* $ZNAME()::                            Unknown.
* $ZNEXT()::                            Unknown.
* $ZORDER()::                           Unknown.
* $ZPIECE()::                           Unknown.
* $ZPREVIOUS()::                        Unknown.
* $ZREPLACE()::                         Replace all instances of a substring within a string.
* $ZSYNTAX()::                          Perform syntax check on string argument.
* $ZTIME()::                            Convert a @code{@ref{$HOROLOG}} string into human-readable time.
@end menu

@node $ASCII()
@section $ASCII
@cindex $ASCII
@cindex intrinsic functions, $ASCII

Returns the ASCII code (in decimal) for one character in a string.

@example
SET RESULT=$ASCII(@emph{<string>}[,@emph{<index>}])
@end example


If @emph{<index>} is not supplied, @code{$ASCII} will return the ASCII code of the first character. Otherwise, returns the ASCII code of the character at position @emph{<index>}.

@node $CHAR()
@section $CHAR
@cindex $CHAR
@cindex intrinsic functions, $CHAR

Returns a string of characters corresponding to a list of ASCII codes.

@example
SET RESULT=$CHAR(@emph{<ascii-code>}[,@emph{<ascii-code>},...])
@end example

@node $DATA()
@section $DATA
@cindex $DATA
@cindex intrinsic functions, $DATA

Returns a numeric value 0, 1, 10, or 11, depending on whether a referenced node is defined, has data, or has children:

@example
SET RESULT=$DATA(@emph{<node>})
@end example

The return values are as follows:

@example
0: @emph{<node>} is undefined
1: @emph{<node>} has data but no children
10: @emph{<node>} has children but no data
11: @emph{<node>} has children and data
@end example

@node $EXTRACT()
@section $EXTRACT
@cindex $EXTRACT
@cindex intrinsic functions, $EXTRACT

Extracts a substring of a string.

The first argument is the source string.

The optional second argument specifies the starting position of the substring to extract, and defaults to @code{1}.

The optional third argument specifies the ending position of the substring to extract, and defaults to the value of the second argument, or @code{1}.

This example will extract the string @emph{FreeM} into the local variable @code{M}.

@example
SET NAME="FreeM is the best!"
SET M=$EXTRACT(NAME,1,5)
@end example

It is also possible to use @code{$EXTRACT} on the left-hand side of a @code{SET} assignment in order to modify a substring:

@example
USER> SET FOO="ABCDEFG"


USER> SET $EXTRACT(FOO,1,3)="XYZ"


USER> WRITE FOO

XYZDEFG
@end example

@node $FIND()
@section $FIND
@cindex $FIND
@cindex intrinsic functions, $FIND

Finds the character immediately following the first occurence of a substring within a string.

The first argument is the source string.

The second argument is the substring to be located.

The optional third argument indicates the position within the source string at which to begin searching.

@node $FNUMBER()
@section $FNUMBER
@cindex $FNUMBER
@cindex intrinsic functions, $FNUMBER

Formats a number according to a particular set of formatting codes.

The first argument is the number to format.

The second argument is the series of formatting codes.

@node $GET()
@section $GET
@cindex $GET
@cindex intrinsic functions, $GET

Returns the value of a local, global, or SSVN if the specified item is defined, or a default value otherwise.

The first argument is the local, global, or SSVN to be examined.

The optional second argument is the default value to be returned if the referenced item is undefined, and defaults to the empty string.

@node $INSTANCEOF()
@section $INSTANCEOF
@cindex $INSTANCEOF
@cindex intrinsic functions, $INSTANCEOF
@cindex object functions, $INSTANCEOF

Returns @code{1} if the specified @emph{lvn} is an instance of class @emph{class}, or @code{0} otherwise.

The first argument is a string representing a valid FreeM local variable.

The second argument is a string representing a valid FreeM class.



@example
USER> N STR=$$^%STRING

USER> W $INSTANCEOF("STR","^%STRING")
1
@end example

@node $JUSTIFY()
@section $JUSTIFY
@cindex $JUSTIFY
@cindex intrinsic functions, $JUSTIFY

Right-justifies a string based on a specified fixed length.

The first argument is the source string.

The second argument is the character length of the output.

The optional third argument controls the number of fractional digits to be included in the output, and defaults to the number of digits specified in the first argument.

@node $LENGTH()
@section $LENGTH
@cindex $LENGTH
@cindex intrinsic functions, $LENGTH

Returns the length of a string, or the number of items in a list delimited by a specified character (as used by @code{@ref{$PIECE()}}).

The first argument is the source string.

The optional second argument is the list delimiter to be used. When this argument is omitted, the length of the string in characters is returned.

@node $NAME()
@section $NAME
@cindex $NAME
@cindex intrinsic functions, $NAME

Returns the canonical name reference along with some or all of its subscripts.

The first argument is the source name.

The optional second argument indicates the maximum subscript count to be returned, and defaults to the subscript count of the source name.

@node $NEXT()
@section $NEXT
@cindex $NEXT
@cindex intrinsic functions, $NEXT

@node $ORDER()
@section $ORDER
@cindex $ORDER
@cindex intrinsic functions, $ORDER

@node $PIECE()
@section $PIECE
@cindex $PIECE
@cindex intrinsic functions, $PIECE

@emph{Syntax}

@code{$PIECE(@emph{s},@emph{d}[,@emph{n}[,@emph{end}]])}

Accesses the @code{n}th through @code{end} @code{d}-delimited pieces of string @code{s}.

The first argument is the string to be evaluated.

The second argument is the delimiter to be used.

The optional third argument is the first @code{d}-delimited piece to access, and defaults to @code{1}.

The optional fourth argument is the final @code{d}-delimited piece to access, and defaults to the value of the third argument (@code{n}).

Can be used on the left-hand side of an expression in order to @code{@ref{SET}} a value into a @code{d}-delimited piece of @code{s}, as in:

@example
; ^jpw="this^is^a^piece"
SET $PIECE(^jpw,"^",2)="isn't" ; => "this^isn't^a^piece"
@end example

@node $QLENGTH()
@section $QLENGTH
@cindex $QLENGTH
@cindex intrinsic functions, $QLENGTH

@emph{Syntax}

@example
@code{$QLENGTH(@emph{expr V glvn})}
@end example

Returns the number of subscripts in @emph{glvn}.

@emph{Example}
@example
@code{SET SUBCT=$QLENGTH("^GBL(1,2,3)") ; => 3}
@end example

@node $QSUBSCRIPT()
@section $QSUBSCRIPT
@cindex $QSUBSCRIPT
@cindex intrinsic functions, $QSUBSCRIPT

@emph{Syntax}

@example
@code{$QSUBSCRIPT(@emph{expr V glvn},@emph{expr V n})}
@end example

Returns the @emph{n}th subscript of @emph{glvn}.

@emph{Example}

@example
@code{SET SUB=$QSUBSCRIPT("^GBL(1,2,3)",2) ; => 2}
@end example

@node $QUERY()
@section $QUERY
@cindex $QUERY
@cindex intrinsic functions, $QUERY

Returns the next subscripted reference in a global.

@emph{Syntax}

@example
@code{$QUERY(@emph{glvn})}
@end example

@emph{Example}

We will assume the following data structure exists:
@example
^jpw(1)=1
^jpw(1,2)="foo"
^jpw(2)=3
^jpw(3)=""
@end example

The following code will retrieve the next subscripted name after @code{^jpw(1)}:

@example
@code{SET NEXTNAM=$QUERY(^jpw(1)) ; => ^jpw(1,2)}
@end example

@node $RANDOM()
@section $RANDOM
@cindex $RANDOM
@cindex intrinsic functions, $RANDOM

@emph{Syntax}

@example
$RANDOM(@emph{max})
@end example

Returns a pseudo-random integer in the range of @code{0..@emph{max} - 1} 

@node $REVERSE()
@section $REVERSE
@cindex $REVERSE
@cindex intrinsic functions, $REVERSE

@emph{Syntax}

@example
$REVERSE(@emph{s})
@end example

Returns the reverse of string @emph{s}.

@emph{Example}

@example
SET FOO=$REVERSE("ABC") ; => CBA
@end example

@node $SELECT()
@section $SELECT
@cindex $SELECT
@cindex intrinsic functions, $SELECT

Returns a value corresponding to the first true condition in a list of conditional expressions. Each argument is an expression, followed by a colon, followed by an expression whose value will be returned if the first expression is true. If no expressions are true, error condition @code{M4} is raised.

@emph{Example}

@example
SET FOO=$SELECT(1=2:"math is broken",1=1:"the world makes sense") ; => "the world makes sense"
@end example

@node $STACK()
@section $STACK
@cindex $STACK
@cindex intrinsic functions, $STACK

Returns information about the program execution stack. The @code{$STACK} intrinsic function has both a one-argument form and a two-argument form.

@emph{Syntax (One-Argument)}

@example
 $STACK(@emph{<num>})
@end example

If @emph{num} is @code{0}, returns the command with which this FreeM instance was invoked.

If @emph{num} is @code{-1}, returns the current program execution stack level.

If @emph{num} represents a valid program execution stack depth above @code{0}, returns one of the following values indicating the reason for which the referenced program execution stack level was created:

@table @asis

@item @code{$$}
If @code{$STACK(@emph{<num>})="$$"}, program execution stack level @code{num} was created as the result of an extrinsic function call

@item @emph{<m-command>}
If @code{$STACK(@emph{<num>})} returns a valid M command, the referenced program execution stack level was created as a result of the @emph{m-command} command.

@end table

@emph{Syntax (Two-Argument})

@example
 $STACK(@emph{<num>},"[ECODE|MCODE|PLACE]")
@end example

Returns the error codes, M program code, or entryref applicable to the action that created program execution stack level @emph{num}.

@node $TEXT()
@section $TEXT
@cindex $TEXT
@cindex intrinsic functions, $TEXT

Returns a line of code from a routine.

@node $TRANSLATE()
@section $TRANSLATE
@cindex $TRANSLATE
@cindex intrinsic functions, $TRANSLATE

@node $TYPE()
@section $TYPE
@cindex $TYPE
@cindex intrinsic functions, $TYPE
@cindex object functions, $TYPE

Returns a string giving the class of the object specified in the parameter.

@xref{Object-Oriented Programming}

@node $VIEW()
@section $VIEW
@cindex $VIEW
@cindex intrinsic functions, $VIEW

@node $ZBOOLEAN()
@section $ZBOOLEAN
@cindex $ZBOOLEAN
@cindex intrinsic functions, $ZBOOLEAN
@cindex intrinsic functions, implementation-specific


Performs @emph{boolean-operation} on numeric arguments @emph{A} and @emph{B}.

@emph{Syntax}

@example
SET RESULT=$ZBOOLEAN(@emph{A},@emph{B},@emph{boolean-operation})
@end example

@code{$ZBOOLEAN} Operations (@emph{boolean-operation} values)

@table @code
@item 0
Always @emph{false}
@item 1
@code{A AND B}
@item 2
@code{A AND NOT B}
@item 3
@code{A}
@item 4
@code{NOT A AND B}
@item 5
@code{B}
@item 6
@code{A XOR B}
@item 7
@code{A OR B}
@item 8
@code{A NOR B}
@item 9
@code{A EQUALS B}
@item 10
@code{NOT B}
@item 11
@code{A OR NOT B}
@item 12
@code{NOT A}
@item 13
@code{NOT A OR B}
@item 14
@code{A NAND B}
@item 15
Always @emph{true}
@end table

@node $ZCALL()
@section $ZCALL
@cindex $ZCALL
@cindex intrinsic functions, $ZCALL
@cindex intrinsic functions, implementation-specific

@node $ZCRC()
@section $ZCRC
@cindex $ZCRC
@cindex intrinsic functions, $ZCRC
@cindex intrinsic functions, implementation-specific

Returns a checksum of @code{arg1}.

@emph{Syntax}

@code{$ZCRC(@emph{arg1})}

@code{SET VAR=$ZCRC("MUMPS") ; => 86}

@node $ZDATA()
@section $ZDATA
@cindex $ZDATA
@cindex intrinsic functions, $ZDATA
@cindex intrinsic functions, implementation-specific

@node $ZDATE()
@section $ZDATE
@cindex $ZDATE
@cindex intrinsic functions, $ZDATE
@cindex intrinsic functions, implementation-specific

Converts a @code{@ref{$HOROLOG}} string into a human-readable date.

@emph{Syntax}

@example
SET VAR=$ZDATE($H[,@emph{<format-string>}])
@end example

The optional @emph{<format-string>} follows the same rules as the UNIX @code{strftime} function. If @emph{<format-string>} is omitted, the value of @code{^$SYSTEM("ZDATE_FORMAT")} is used (typically @code{%x}).

@xref{^$SYSTEM}

@node $ZEDIT()
@section $ZEDIT
@cindex $ZEDIT
@cindex intrinsic functions, $ZEDIT
@cindex intrinsic functions, implementation-specific

@node $ZHOROLOG()
@section $ZHOROLOG
@cindex $ZHOROLOG
@cindex intrinsic functions, $ZHOROLOG
@cindex intrinsic functions, implementation-specific

Converts date and/or time values producible by @code{@ref{$ZDATE()}} or @code{@ref{$ZTIME()}} to @code{@ref{$HOROLOG}} format.

@emph{Syntax}

@example
$ZHOROLOG(@emph{<date-value>},@emph{<format-string>})
@end example

@emph{<date-value>} is a date or time string compatible with the formats from @code{@ref{$ZDATE()}} or @code{@ref{$ZTIME}}.

@emph{<format-string>} is a format string of the same format as used by the @code{strptime(3)} UNIX function.

@node $ZKEY()
@section $ZKEY
@cindex $ZKEY
@cindex intrinsic functions, $ZKEY
@cindex intrinsic functions, implementation-specific

@node $ZLENGTH()
@section $ZLENGTH
@cindex $ZLENGTH
@cindex intrinsic functions, $ZLENGTH
@cindex intrinsic functions, implementation-specific

@node $ZLSD()
@section $ZLSD
@cindex $ZLSD
@cindex intrinsic functions, $ZLSD
@cindex intrinsic functions, implementation-specific

Returns the Levenshtein distance between two arguments. The Levenshtein distance represents the minimum number of edits needed to change the first argument into the second argument.

@emph{Syntax}

@code{SET VAR=$ZLSD(@emph{arg1},@emph{arg2})}

@emph{Example}

@code{SET VAR=$ZLSD("KITTENS","MITTENS") ; => 1}

@node $ZM()
@section $ZM
@cindex $ZM
@cindex intrinsic functions, $ZM
@cindex intrinsic functions, implementation-specific

@node $ZNAME()
@section $ZNAME
@cindex $ZNAME
@cindex intrinsic functions, $ZNAME
@cindex intrinsic functions, implementation-specific

@node $ZNEXT()
@section $ZNEXT
@cindex $ZNEXT
@cindex intrinsic functions, $ZNEXT
@cindex intrinsic functions, implementation-specific

@node $ZORDER()
@section $ZORDER
@cindex $ZORDER
@cindex intrinsic functions, $ZORDER
@cindex intrinsic functions, implementation-specific

@node $ZPIECE()
@section $ZPIECE
@cindex $ZPIECE
@cindex intrinsic functions, $ZPIECE
@cindex intrinsic functions, implementation-specific

@node $ZPREVIOUS()
@section $ZPREVIOUS
@cindex $ZPREVIOUS
@cindex intrinsic functions, $ZPREVIOUS
@cindex intrinsic functions, implementation-specific

@node $ZREPLACE()
@section $ZREPLACE
@cindex $ZREPLACE
@cindex intrinsic functions, $ZREPLACE
@cindex intrinsic functions, implementation-specific

Replaces all instances of @code{arg2} with @code{arg3} in string @code{arg1}.

@emph{Syntax}
@code{$ZREPLACE(@emph{arg1},@emph{arg2},@emph{arg3})}

@emph{Example}

@code{SET VAR=$ZREPLACE("CAT","C","B") ; => BAT}

@node $ZSYNTAX()
@section $ZSYNTAX
@cindex $ZSYNTAX
@cindex intrinsic functions, $ZSYNTAX
@cindex intrinsic functions, implementation-specific

@code{$ZSYNTAX} performs a very basic syntax check on @emph{expr V mcode}. Checks only for illegal commands, mismatched brackets, mismatched quotes, missing or surplus arguments, or surplus commas.

@emph{Syntax}
@example
$ZSYNTAX(@emph{expr V mcode})
@end example

If no syntax error is found, returns the empty string.

If a syntax error is found, returns a number indicating the position in @emph{expr V mcode} at which the error was found, followed by a comma, and the FreeM error code that was found.

@node $ZTIME()
@section $ZTIME
@cindex $ZTIME
@cindex intrinsic functions, $ZTIME
@cindex intrinsic functions, implementation-specific

Converts a @code{@ref{$HOROLOG}} string into a human-readable time.

@emph{Syntax}

@example
SET VAR=$ZTIME($H[,@emph{<format-string>}])
@end example

The optional @emph{<format-string>} follows the same rules as the UNIX @code{strftime(3)} function. If @emph{<format-string>} is omitted, the value of @code{^$SYSTEM("ZTIME_FORMAT")} is used (typically @code{%X}).

@node OBJECT Methods
@chapter OBJECT Methods

These methods are part of the @code{^%OBJECT} class, from which all FreeM objects ultimately inherit.

Please note that classes may override @code{^%OBJECT} methods (or methods of any class) in order to provide results more fitting to the class's abstraction goals.

@menu
* $$TONUMBER::          Returns the canonical numeric representation of the object.
* $$TYPE::              Returns the fully-qualified class name of the object.
* $$VALUE::             Returns the value of the object.
@end menu

@node $$TONUMBER
@section $$TONUMBER

Returns (when applicable) a canonical numeric representation of the referenced object.

@emph{Syntax}

@example
W $$MYOBJECT.TONUMBER(),!
@end example

If no canonical numeric representation of the object is possible, will return the empty string.

@node $$TYPE
@section $$TYPE

Returns the fully-qualified class of the referenced object.

@emph{Syntax}

@example
W $$MYOBJECT.TYPE()
@end example

Note that M variables that are created by non-object-oriented means will be objects of the @code{^%STRING} class.

@node $$VALUE
@section $$VALUE

Returns the value of the referenced object.

@emph{Syntax}

@example
W $$MYOBJECT.VALUE()
@end example

@node STRING Methods
@chapter STRING Methods

These are methods inherent to the @code{^%STRING} class, which is the default class for M variables created without specifying a class.

@menu
* $$ASCII::             Return the ASCII code of a character within the string.
* $$DATA::              Return tree characteristics of the string.
* $$DISTANCE::          Determine Levenstein distance between this string and another.
* $$EXTRACT::           Return a substring of the string.
* $$FIND::              Find the position of a substring within the string.
* $$FNUMBER::           Format numbers.
* $$JUSTIFY::           Pad the string to specific positions.
* $$LENGTH::            Return the length of the string.
* $$PIECECOUNT::        Return the count of pieces existing between instances of a delimiter.
* $$PIECE::             Return a delimited subset of the string.
* $$REPLACE::           Replace instances of a substring within the string.
* $$REVERSE::           Reverse the order of characters in the string.
* $$TOLOWER::           Return a lowercase version of the string.
* $$TOUPPER::           Return an uppercase version of the string.
* $$TRANSLATE::         Replace individual characters within the string.
@end menu

@node $$ASCII
@section $$ASCII

Returns the ASCII code of a character within the string. See @ref{$ASCII()}.

@emph{Syntax}

@example
W $$MYOBJECT.ASCII(3)
@end example

The above example returns the ASCII code in position 3 of string object @code{MYOBJECT}.

@node $$DATA
@section $$DATA

Returns the value of the @code{$DATA} intrinsic function as performed on the value of the object. See @ref{$DATA()}.

@emph{Syntax}

@example
W $$MYOBJECT.DATA()
@end example

@node $$DISTANCE
@section $$DISTANCE

Returns the Levenstein distance between the string and another string. See @ref{$ZLSD()}.

@emph{Syntax}

@example
W $$MYOBJECT.DISTANCE("someString")
@end example

@node $$EXTRACT
@section $$EXTRACT

Returns a substring of the string. See @ref{$EXTRACT()}.

@emph{Syntax}

@example
$$<objectName>.EXTRACT(<start>,<end>)
@end example


@node $$FIND
@section $$FIND

@node $$FNUMBER
@section $$FNUMBER

@node $$JUSTIFY
@section $$JUSTIFY

@node $$LENGTH
@section $$LENGTH

@node $$PIECECOUNT
@section $$PIECECOUNT

@node $$PIECE
@section $$PIECE

@node $$REPLACE
@section $$REPLACE

@node $$REVERSE
@section $$REVERSE

@node $$TOLOWER
@section $$TOLOWER

@node $$TOUPPER
@section $$TOUPPER

@node $$TRANSLATE
@section $$TRANSLATE

@node Commands
@chapter Commands
@cindex commands

@menu
* @@::                                  Execute the following expression as M code.
* !::                                   Run an external program or command.
* !!::                                  Launch a subshell from FreeM direct mode.
* ABLOCK::                              Increment the block counter for one or more event classes.
* ASSERT::                              Raise error when a conditional expression evaluates @emph{false}.
* ASTART::                              Enable asynchronous event handling for one or more event classes.
* ASTOP::                               Disable asynchronous event handling for one or more event classes.
* AUNBLOCK::                            Decrement the block counter for one or more event classes.
* BREAK::                               Interrupt a running routine to allow interactive debugging.
* CLOSE::                               Close an input/output device.
* CONST::                               Define a constant that cannot be altered after initial definition.
* DO::                                  Transfer program control to one or more subroutines or introduces a new execution level.
* ELSE::                                Execute the remainder of a line if @code{@ref{$TEST}} evaluates @emph{false}.
* FOR::                                 Repeat execution of a line or block of code.
* GOTO::                                Unconditionally transfer program execution to a supplied @emph{entryref}.
* HALT::                                Terminate the current FreeM interpreter instance.
* HANG::                                Temporarily suspend the running program.
* IF::                                  Execute the remainder of a line if a conditional expression evaluates @emph{true}.
* JOB::                                 Execute an @emph{entryref} in a child process.
* KILL::                                Remove data from a local, global, or structured system variable.
* KSUBSCRIPTS::                         Kill only the descendant subscripts of a local, global, global, or structured system variable.
* KVALUE::                              Kill only the value of a local, global, or structured system variable.
* LOCK::                                Control advisory locking for concurrency control.
* MAP::                                 Map a global name to a non-default namespace.
* MERGE::                               Merge contents of one local, global, or structured system variable into another.
* NEW::                                 Introduce a new scope for a specified local variable or intrinsic special variable or instantiate an object.
* OPEN::                                Open a sequential or socket input/output device.
* QUIT::                                End execution of the current process level, optionally with return value.
* READ::                                Read input from an input/output device.
* SET::                                 Set the value of a local variable, global, intrinsic special variable, or structured system variable.
* TCOMMIT::                             Commit a transaction.
* THEN::                                Preserve @code{@ref{$TEST}} until the end of the current line.
* THROW::                               Programmatically raise an error condition.
* TROLLBACK::                           Roll back all pending transactions.
* TSTART::                              Introduce a new transaction processing level.
* UNMAP::                               Remove a mapping of a global to a non-default namespace.
* USE::                                 Set the currently-active input/output device.
* VIEW::                                Modify FreeM internal parameters.
* WATCH::                               Enable or disable watchpoints, or set or clear watchpoints on specified globals, locals, or structured system variables.
* WITH::                                Set prefix for future variable references.
* WRITE::                               Write output to current input/output device.
* XECUTE::                              Interpret string as M code.
* ZALLOCATE::                           Alternative to @code{LOCK}.
* ZBREAK::                              Unknown.
* ZDEALLOCATE::                         Alternative to @code{LOCK}.
* ZGO::                                 Unknown.
* ZHALT::                               Unknown.
* ZINSERT::                             Insert code into routine buffer.
* ZJOB::                                Unknown.
* ZLOAD::                               Load routine into routine buffer.
* ZNEW::                                Unknown.
* ZPRINT::                              Print contents of routine buffer.
* ZQUIT::                               Unknown.
* ZREMOVE::                             Remove code from routine buffer.
* ZSAVE::                               Save routine buffer to disk.
* ZTRAP::                               Unknown.
* ZWRITE::                              Write local variable, global, or structured system variable to @code{@ref{$IO}}.
@end menu

@node @@
@section @@
@cindex @@
@cindex commands, @@
@cindex commands, implementation-specific
@cindex commands, non-standard

Executes FreeM code @emph{expr V mcode}.

@emph{Syntax}

@example
@@@emph{expr V mcode}
@end example

@emph{Example (Using Variable)}

@example
USER> SET FOO="WRITE ""HELLO WORLD"",!"
USER> @@FOO

HELLO WORLD

USER>
@end example

@emph{Example (Using String Literal)}

@example
USER> @@"WRITE ""HELLO WORLD"",!"

HELLO WORLD

USER>
@end example

@emph{Example (Using Indirection)}

@example
USER> SET FOO="BAR"

USER> SET BAR="WRITE ""HELLO WORLD"",!"

USER> @@@@FOO

HELLO WORLD

USER>
@end example


@node !
@section !
@cindex !
@cindex commands, !
@cindex commands, external
@cindex commands, non-standard
@emph{FreeM Extension}

Invokes a shell to run @emph{<external-command>} from within FreeM. This temporarily disables @command{SIGALRM} handling in FreeM, which may interrupt the use of event-driven M programming commands including @command{ESTART} and @command{ESTOP}.

If the @command{<} character is supplied immediately preceding @emph{<external-command>}, FreeM will append the contents of M local variable @code{%} to @emph{<external-command>} as standard input.

If the @command{>} character is supplied immediately preceding @emph{<external-command>}, FreeM will take the standard output stream of @emph{<external-command>} and store it in M local variable @code{%}.

@code{%} contains the number of lines in the input or output. @code{%(1)..%(@emph{n})} contains the data for lines 1-@emph{n}.

@node !!
@section !!
@cindex !!
@cindex commands, !!
@cindex commands, external
@cindex commands, non-standard
@emph{FreeM Extension}

Launches a subshell within the FreeM direct mode, allowing the user to run operating system commands.

@example
USER> !!

Type Ctrl-D to exit from the shell
$ uname -a
Linux hesperos 4.19.0-17-amd64 #1 SMP Debian 4.19.194-3 (2021-07-18) x86_64 GNU/Linux
$ exit

USER> 
@end example


@node ABLOCK
@section ABLOCK
@cindex ABLOCK
@cindex commands, ABLOCK

Increments the event block counter for one or more event classes. While the block counter for an event class is greater than zero, registered event handlers for that event class will not execute, and will instead be queued for later execution once the block counter reaches zero (all blocks removed).

An implicit @code{ABLOCK} on all event classes occurs when an event handler subroutine is executing. As soon as a @code{QUIT} is reached within an event handler, an implicit @code{ABLOCK} will occur.

@emph{Syntax}

@example
  ABLOCK@emph{:postcondition}
@end example

In its argumentless form, @code{ABLOCK} increments the block counter for @emph{all} event classes, provided the optional @emph{postcondition} is either @emph{true} or omitted.

@example
  ABLOCK@emph{:postcondition} @emph{evclass1}...,@emph{evclassN}
@end example

In its inclusive form, @code{ABLOCK} increments the block counters for all event classes named in the list, provided the optional @emph{postcondition} is either @emph{true} or omitted.

@example
  ABLOCK@emph{:postcondition} (@emph{evclass1}...,@emph{evclassN}
@end example

In its exclusive form, @code{ABLOCK} increments the block counters for all event classes @emph{except for} those named in the list, provided the optional @emph{postcondition} is either @emph{true} or omitted.

@node ASSERT
@section ASSERT
@cindex ASSERT
@cindex commands, ASSERT
@cindex commands, debugging
@cindex commands, implementation-specific
@cindex commands, non-standard
@emph{FreeM Extension}

Triggers error @code{ASSERT} if the supplied truth-valued expression @emph{tvexpr} is @emph{false} (@emph{1} is @emph{true}, and @emph{0} is @emph{false}), and that the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

The @code{ASSERT} error is catchable whether using standard-style, FreeM-style, or DSM 2.0-style error processing.

@emph{Syntax}

@example
 ASSERT@emph{:postcondition} @emph{<tvexpr>}
@end example

@emph{Example}

@example
USER> SET DEBUG=1


USER> ASSERT:DEBUG 1=1


USER> ASSERT:DEBUG 1=0
 
 
>> Error ZASSERT:  programmer assertion failed in SYSTEM::^%SYSINIT  [$STACK = 0]
>> ASSERT:DEBUG 1=0
                   ^
@end example

@node ASTART
@section ASTART
@cindex ASTART
@cindex commands, ASTART

Enables asynchronous event handling for one or more event classes.

@emph{Syntax}

@example
  ASTART@emph{:postcondition}
@end example

In its argumentless form, @code{ASTART} enables asynchronous event handling for all event classes, provided the optional @emph{postcondition} is either @emph{true} or omitted.

@example
  ASTART@emph{:postcondition} @emph{evclass1}...,@emph{evclassN}
@end example

In its inclusive form, @code{ASTART} enables asynchronous event handling for all event classes named in the list, provided the optional @emph{postcondition} is either @emph{true} or omitted.

@example
  ASTART@emph{:postcondition} (@emph{evclass1}...,@emph{evclassN})
@end example

In its exclusive form, @code{ASTART} enables asynchronous event handling for all event classes @emph{except for} those named in the list, provided the optional @emph{postcondition} is either @emph{true} or omitted.

@node ASTOP
@section ASTOP
@cindex ASTOP
@cindex commands, ASTOP

Disables asynchronous event handling for one or more event classes.

@emph{Syntax}

@example
  ASTOP@emph{:postcondition}
@end example

In its argumentless form, @code{ASTOP} disables asynchronous event handling for all event classes, provided the optional @emph{postcondition} is either @emph{true} or omitted.

@example
  ASTOP@emph{:postcondition} @emph{evclass1}...,@emph{evclassN}
@end example

In its inclusive form, @code{ASTOP} disables asynchronous event handling for all event classes named in the list, provided the optional @emph{postcondition} is either @emph{true} or omitted.

@example
  ASTOP@emph{:postcondition} (@emph{evclass1}...,@emph{evclassN})
@end example

In its exclusive form, @code{ASTOP} disables asynchronous event handling for all event classes @emph{except for} those named in the list, provided the optional @emph{postcondition} is either @emph{true} or omitted.

@node AUNBLOCK
@section AUNBLOCK
@cindex AUNBLOCK
@cindex commands, AUNBLOCK

Decrements the event block counter for one or more event classes.

@emph{Syntax}

@example
  AUNBLOCK@emph{:postcondition}
@end example

In its argumentless form, @code{AUNBLOCK} decrements the block counter for @emph{all} event classes, provided the optional @emph{postcondition} is either @emph{true} or omitted.

@example
  AUNBLOCK@emph{:postcondition} @emph{evclass1}...,@emph{evclassN}
@end example

In its inclusive form, @code{AUNBLOCK} decrements the block counters for all event classes named in the list, provided the optional @emph{postcondition} is either @emph{true} or omitted.

@example
  AUNBLOCK@emph{:postcondition} (@emph{evclass1}...,@emph{evclassN}
@end example

In its exclusive form, @code{AUNBLOCK} decrements the block counters for all event classes @emph{except for} those named in the list, provided the optional @emph{postcondition} is either @emph{true} or omitted.


@node BREAK
@section BREAK
@cindex BREAK
@cindex commands, BREAK

Interrupts running routine to allow interactive debugging.

@emph{Syntax}

@example
@code{BREAK@emph{:postcondition}}
@end example

In its argumentless form, @code{BREAK} suspends execution of running code, provided the optional @emph{postcondition} is @emph{true} or omitted.

@example
@code{BREAK@emph{:postcondition} @emph{breakflag}}
@end example

@emph{FreeM Extension}

In its single-argument form, @code{BREAK} sets @emph{Ctrl-C} handling and error handling characteristics, provided the optional @emph{postcondition} is @emph{true} or omitted.
The following table enumerates the possible values of @emph{breakflag}

@table @code
@item 0
Disables @emph{Ctrl-C} handling
@item -2
Enables normal FreeM error handling
@item 2
Enables @emph{Digital Standard MUMPS} v2 error handling
@item @emph{any integer value other than 0, 2, or -2}
Enables @emph{Ctrl-C} handling
@end table

@node CLOSE
@section CLOSE
@cindex CLOSE
@cindex commands, CLOSE

Closes an input/output device.

@emph{Syntax}

@example
@code{CLOSE@emph{:postcondition}}
@end example

In its argumentless form, @code{CLOSE} closes all I/O devices except for device 0 (the @code{HOME} device), provided the optional @emph{postcondition} is @emph{true} or omitted.

@example
@code{CLOSE@emph{:postcondition} @emph{channel}}
@end example

In its single-argument form, @code{CLOSE} closes the I/O device associated with channel @emph{channel}, provided that @emph{channel} represents a currently-open device, and the optional @emph{postcondition} is @emph{true} or omitted.

@node CONST
@section CONST
@cindex CONST
@cindex commands, CONST
@cindex commands, non-standard
@emph{FreeM Extension}

Defines a local @emph{constant}, or variable that cannot be altered after its initial definition, provided the optional @emph{postcondition} is @emph{true} or omitted.

Constants must only be locals, and globals are not supported.

@emph{Syntax}

@example
@code{CONST@emph{:postcondition} @emph{mref1}=@emph{initial-value1},...,@emph{mrefN}=@emph{initial-valueN}}
@end example

@node DO
@section DO
@cindex DO
@cindex commands, DO

In its inclusive form, transfers program control to one or more specified subroutines, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted. Line levels of entryrefs specified in the argument list must be one, or error @code{M14} is raised.

@emph{Syntax}

@example
DO[@emph{:postcondition}] @emph{entryref}[@emph{:postcondition}[,...]]
@end example

In its argumentless form, transfers control to the following block of code where the line level is one greater than the level at which @code{DO} was encountered, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

@emph{Syntax}

@example
DO[@emph{:postcondition}]
@end example

@node ELSE
@section ELSE
@cindex ELSE
@cindex commands, ELSE

Executes the remainder of the line of code on which @code{ELSE} is encountered only if @code{$TEST} evaluates to @emph{false}, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

@emph{Syntax}

@example
ELSE[@emph{:postcondition}]
@end example

@cartouche
@quotation
@emph{Non-Standard Behavior}

FreeM allows a @emph{postcondition} on @code{ELSE}. While explicitly forbidden in the @emph{standard}--and for good reason--it was decided that FreeM should allow postconditions everywhere, both for the sake of foolish consistency (the likes of which Emerson warned against), and for the benefit of entrants to a hypothetical future obfuscated M contest, and those with a Machiavellian predisposition to wicked perversions and undue cleverness.

Using postconditions on @code{ELSE} should be strictly avoided in production code, as they have no practical use, and may contribute to technical debt, hardening of the arteries, hobgoblins, a small mind, a surfeit of logic, climate change, Daily WTF rants, or meltdown of global financial markets.
@end quotation
@end cartouche

@node FOR
@section FOR
@cindex FOR
@cindex commands, FOR

In its argumentless form, repeatedly executes the remainder of the line on which @code{FOR} was encountered until a @code{QUIT}, @code{GOTO}, or end-of-line is encountered, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

@emph{Syntax}

@example
FOR[@emph{:postcondition}]
@end example

@cartouche
@quotation
@emph{Non-Standard Behavior}

When @code{$DIALECT} is set to @code{FREEM}, FreeM allows a @emph{postcondition} on @code{FOR}. Much like postconditions on @code{ELSE} and @code{IF}, this is explicitly forbidden in the @emph{standard}. The expression contained in the @emph{postcondition} is evaluated on each iteration of the @code{FOR} loop, and if it does not evaluate @emph{true}, the loop will be immediately exited. The effect is roughly similar to @code{WHILE} constructs present in other languages, but absent from standard M.

As with all non-standard features of FreeM, please exercise caution when using this feature, especially in code that is expected to run in other, less preternaturally-inclined M implementations.
@end quotation
@end cartouche

In its sentinel form, repeatedly executes the remainder of the line and sets a sentinel variable on each iteration, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

On the first iteration of the loop, @emph{glvn} will be set to @emph{initalizer-expression}. On each subsequent iteration, @emph{glvn} will be incremented by @emph{increment-expression}, and the loop will terminate when @emph{glvn} meets or exceeds the value of @emph{max-expression}.

@emph{Syntax}

@example
FOR[@emph{:postcondition}] @emph{glvn}=@emph{initializer-expression}:@emph{increment-expression}:@emph{max-expression}
@end example

@emph{Example}

@example
USER> FOR I=1:1:10 WRITE I,!

1
2
3
4
5
6
7
8
9
10

USER> FOR I=2:2:10 WRITE I,!

2
4
6
8
10
@end example

In its explicit parameter form, a variable is set to each of a series of explicit values, once per iteration, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted. The loop terminates when no more values are available.

@emph{Syntax}

@example
FOR[@emph{:postcondition}] @emph{glvn}=@emph{expr1}[,..@emph{exprN}]
@end example

@emph{Example}

@example
USER> FOR I=60,"FOO",-3,"George",1450,$HOROLOG WRITE I,!

60
FOO
-3
George
1450
66106,52388
@end example

@node GOTO
@section GOTO
@cindex GOTO
@cindex commands, GOTO

Transfers program execution to another line of code, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted. Attempting to @code{GOTO} a different line level or a different block when the line level of @code{GOTO} is greater than one will raise error @code{M45}.

@emph{Syntax}

@example
GOTO[@emph{:postcondition}] @emph{entryref}
@end example

@node HALT
@section HALT
@cindex HALT
@cindex commands, HALT

Halts program execution and frees resources allocated during execution, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

@emph{Syntax}

@example
HALT[@emph{:postcondition}]
@end example

@node HANG
@section HANG
@cindex HANG
@cindex commands, HANG

Temporarily suspends the program for @emph{expr} seconds, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted. Values of @emph{expr} that are zero or less than zero are ignored.

@emph{Syntax}

@example
HANG[@emph{:postcondition}] @emph{expr}
@end example

@cartouche
@quotation
@emph{Non-Standard Behavior}

FreeM supports sub-second values for @emph{expr}.
@end quotation
@end cartouche

@node IF
@section IF
@cindex IF
@cindex commands, IF

In its argumented form, allows the remainder of the line of code following @code{IF} to execute only if all @emph{tvexpr}s evaluate to @emph{true}, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

@emph{Syntax}
@example
IF[@emph{:postcondition}] @emph{tvexpr}[,...@emph{tvexpr}]
@end example

In its argumentless form, allows the remainder of the line of code following @code{IF} to execute only if @code{$TEST} evaluates to @emph{1}, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

@emph{Syntax}
@example
IF[@emph{:postcondition}]
@end example

@node JOB
@section JOB
@cindex JOB
@cindex commands, JOB

Executes @emph{entryref} in a separate process, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

@emph{Syntax}
@example
JOB[@emph{:postcondition}] @emph{entryref}[:@emph{job-parameters}[:@emph{timeout}]]
@end example

If @emph{timeout} is supplied, FreeM will set @code{$TEST} to @emph{1} if the child process completes within @emph{timeout} seconds.

@node KILL
@section KILL
@cindex KILL
@cindex commands, KILL

In its inclusive form, @code{KILL} deletes the specified @emph{glvn}s and their descendant subscripts, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

@emph{Syntax}
@example
KILL[@emph{:postcondition}] @emph{glvn}[,...@emph{glvn}]
@end example

In its exclusive form, @code{KILL} deletes all local variables @emph{except} for those specified by @emph{lvn}, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

@emph{Syntax}
@example
KILL[@emph{:postcondition}] (@emph{lvn}[,...@emph{lvn}])
@end example

In its argumentless form, @code{KILL} deletes all local variables, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

@emph{Syntax}
@example
KILL[@emph{:postcondition}]
@end example

@node KSUBSCRIPTS
@section KSUBSCRIPTS
@cindex KSUBSCRIPTS
@cindex commands, KSUBSCRIPTS

Kills only the descendant subscripts (but not the data value) of a referenced global, local, or SSVN (where allowed).

@emph{Syntax}

@example
KSUBSCRIPTS@emph{:postcondition} @emph{var1},...
@end example

In the above @emph{inclusive} form, @code{KVALUE} will kill the descendant subscripts at each local, global, or SSVN node specified in the list (provided that the optional @emph{postcondition} is @emph{true} or omitted), but will leave the data value intact.

@cartouche
@quotation
@emph{Note}
The below @emph{argumentless} and @emph{exclusive} forms of @code{KSUBSCRIPTS} are not implemented in FreeM, as of version 0.3.3, but are planned for a future release.
@end quotation
@end cartouche

@example
KSUBSCRIPTS@emph{:postcondition}
@end example

In the above @emph{argumentless} form, @code{KSUBSCRIPTS} will kill the descendant subscripts at the root of each local variable (provided that the optional @emph{postcondition} is @emph{true} or omitted), but will leave data values intact.

@example
KSUBSCRIPTS@emph{:postcondition} (@emph{var1},...)
@end example

In the above @emph{exclusive} form, @code{KSUBSCRIPTS} will kill the descendant subscripts of all local variables, @emph{with the exception of} those named in the list, provided that the optional @emph{postcondition} is @emph{true} or omitted, while leaving their data values intact.


@node KVALUE
@section KVALUE
@cindex KVALUE
@cindex commands, KVALUE

Kills only the data value (but not descendant subscripts) of a referenced global, local, or SSVN (where allowed).

@emph{Syntax}

@example
KVALUE@emph{:postcondition} @emph{var1},...
@end example

In the above @emph{inclusive} form, @code{KVALUE} will kill the data values at each local, global, or SSVN node specified in the list (provided that the optional @emph{postcondition} is @emph{true} or omitted), but will leave descendant subscripts intact.

@cartouche
@quotation
@emph{Note}
The below @emph{argumentless} and @emph{exclusive} forms of @code{KVALUE} are not implemented in FreeM, as of version cvs-current, but are planned for a future release.
@end quotation
@end cartouche

@example
KVALUE@emph{:postcondition}
@end example

In the above @emph{argumentless} form, @code{KVALUE} will kill the data values at the root of each local variable (provided that the optional @emph{postcondition} is @emph{true} or omitted), but will leave descendant subscripts intact.

@example
KVALUE@emph{:postcondition} (@emph{var1},...)
@end example

In the above @emph{exclusive} form, @code{KVALUE} will kill the data values of all local variables, @emph{with the exception of} those named in the list, provided that the optional @emph{postcondition} is @emph{true} or omitted, while leaving their descendant subscripts intact.

@node LOCK
@section LOCK
@cindex LOCK
@cindex commands, LOCK

Acquires or releases ownership of names.

In its argumentless form, @code{LOCK} releases ownership of all names previously locked by the current process, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

@emph{Syntax}
@example
LOCK[@emph{:postcondition}]
@end example

In its incremental form, increments or decrements the lock counter for each specified @emph{name}, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted. Ownership of each @emph{name} is considered to be the current process as long as the lock counter for @emph{name} is greater than zero. If @emph{timeout} is specified, FreeM will wait no more than @emph{timeout} seconds in attempting to acquire ownership of @emph{name}.

If @code{LOCK} succeeds within @emph{timeout}, @code{$TEST} is set to @emph{1}. Otherwise, @code{$TEST} is set to @emph{0}.

@emph{Syntax}
@example
LOCK[@emph{:postcondition}] [+|-]@emph{name}[:@emph{timeout}][,...[+|-]@emph{name}[:@emph{timeout}]]
@end example

@emph{Example}

This example will increment the lock counter for @code{^JPW} and decrement the lock counter for @code{^MJR}.

@example
LOCK +^JPW,-^MJR
@end example

In its non-incremental form, @code{LOCK} releases all @code{LOCK}s held by the current process, and then attempts to acquire a lock on each @emph{name}, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted. If @emph{timeout} is supplied, FreeM will attempt to lock @emph{name} for no more than @emph{timeout} seconds.

If @code{LOCK} succeeds within @emph{timeout}, @code{$TEST} is set to @emph{1}. Otherwise, @code{$TEST} is set to @emph{0}.

@emph{Syntax}
@example
LOCK[@emph{:postcondition}] @emph{name}[:@emph{timeout}][,...@emph{name}[:@emph{timeout}]]
@end example

@node MAP
@section MAP
@cindex MAP
@cindex commands, MAP
@cindex commands, implementation-specific
@cindex commands, non-standard

Maps global name @code{gvn} to be mapped to the non-default namespace @emph{expr V namespace}, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

@emph{Syntax}

@example
MAP[@emph{:postcondition}] GLOBAL @emph{gvn}=@emph{expr V namespace}
@end example

@node MERGE
@section MERGE
@cindex MERGE
@cindex commands, MERGE

Merges the contents of one global, local, or SSVN subtree to another global, local, or SSVN.

@emph{Syntax}

@example
@code{MERGE A=^$JOB}
@end example

The above example will merge the @code{^$JOB} SSVN into the @code{A} local. Note that the FreeM implementation of @code{MERGE} does not yet support multiple merge arguments. Returns error @code{M19} if either the source or the target variable are descendants of each other.

@node NEW
@section NEW
@cindex NEW
@cindex commands, NEW

In all forms of @code{NEW}, @emph{name} must be a local variable name or @code{NEW}-able structured or intrinsic system variable.

In its inclusive form, @code{NEW} saves each specified @emph{name} on the process stack and removes it, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.  When the current stack frame is exited, the previous values are restored.

@emph{Syntax}

@example
NEW[@emph{:postcondition}] @emph{name}[,...@emph{name}]
@end example

In its exclusive form, @code{NEW} saves all local variables @emph{except} those named (each @emph{name}) and removes them, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted. When the current stack frame is exited, the previous values are restored.

@emph{Syntax}
@example
NEW[@emph{:postcondition}] (@emph{name}[,...@emph{name}])
@end example

In its argumentless form, @code{NEW} saves all local variables and removes them, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted. When the current stack frame is exited, the previous values are restored.

@emph{Syntax}
@example
NEW@emph{:postcondition} @emph{name}=@emph{expr}
@end example

In its initializing form, @code{NEW} stacks variable @emph{name} and sets its value to @emph{expr}, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted. When the current stack frame is exited, the previous value is restored.

@node OPEN
@section OPEN
@cindex OPEN
@cindex commands, OPEN

Opens sequential or socket I/O devices and files and associates them with a numeric FreeM input/output channel.

@emph{Syntax (Sequential Files)}

@example
@code{OPEN@emph{:postcondition} @emph{channel}:"@emph{filename}/@emph{access-mode}"}
@end example

Opens @emph{filename} for reading and/or writing, and associates the file with FreeM I/O channel @emph{channel}, provided that the optional @emph{postcondition} is @emph{true} or omitted.
The below table lists the valid options for @emph{access-mode}:

@table @code
@item r
Read-only access
@item w
Create a new file for write access
@item a
Write access; append to existing file
@item r+
Read/write access
@end table

@cartouche
@quotation
@emph{I/O Path}

You cannot specify a fully-qualified filesystem path in the FreeM @code{OPEN} command. By default, FreeM will assume that @emph{filename} exists in the directory indicated in @code{^$JOB($JOB,"CWD")}. If you wish to
access files in other directories, you must first set the @emph{I/O Path} in @code{^$JOB($JOB,"IOPATH")}.

The following example will set the I/O path to @code{/etc}:

@example
@code{SET ^$JOB($JOB,"IOPATH")="/etc"}
@end example

@end quotation
@end cartouche

If @emph{channel} was already @code{OPEN}ed in the current process, calling @code{OPEN} on the same channel again implicitly closes the file or device currently associated with @emph{channel}.

@emph{Syntax (Network Sockets)}

Network sockets use a dedicated range of FreeM I/O channels ranging from 100-255. @code{OPEN}ing a socket I/O channel does @emph{not} implicitly connect the socket. Connecting the socket to the specified remote host is accomplished by the @code{/CONNECT} control mnemonic supplied to the @code{USE} command.

@example
  OPEN@emph{:postcondition} @emph{socket-channel}:"@emph{hostname-or-address}:@emph{port}:@emph{address-family}:@emph{connection-type}"
@end example

@emph{Socket Parameters}

@table @emph

@item socket-channel
The socket I/O channel to use. This must be in the range of 100-255.

@item hostname-or-address
The hostname or IP address to connect to. If a hostname is supplied, @code{OPEN} will implictly do a name lookup, the mechanism of which is typically determined by the configuration of @code{/etc/nsswitch.conf} on most UNIX and UNIX-like platforms.

@item port
The TCP or UDP port to which the socket will connect on the remote host.

@item address-family
The address family to use. Either @emph{IPV4} or @emph{IPV6}.

@item connection-type
Which connection type to use. Either @emph{TCP} or @emph{UDP}.

@end table

If you do not specify the address family and connection type, they will default to @emph{IPV4} and @emph{TCP}, respectively.

@node QUIT
@section QUIT
@cindex QUIT
@cindex commands, QUIT

@code{QUIT} will end execution of the current process level, optionally returning @emph{expr}, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

@code{QUIT} with @emph{expr} when an argument is not expected will raise error @code{M16}; @code{QUIT} without @emph{expr} when an argument is expected will raise error @code{M17}.

Argumentless @code{QUIT} may also be used to exit a @code{FOR} loop occurring on the same line.

@emph{Syntax}
@example
QUIT[@emph{:postcondition}] [@emph{expr}]
@end example

@node READ
@section READ
@cindex READ
@cindex commands, READ

The @code{READ} command takes input from I/O channel @code{$IO} and stores it into specified variables, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

@emph{Syntax}
@example
READ[@emph{:postcondition}] @emph{read-argument}[,...@emph{read-argument}]
@end example

Each @emph{read-argument} may be one of the following:

@table @asis

@item String Literal
String literal @emph{read-argument}s will be output to @code{$IO} unmodified.

@item Format Specifier
One or more of the following:

@table @asis
@item @code{!} (newline)
Advances the cursor down by one line and returns it to the first column.

@item @code{#} (form-feed)
Advances the screen down by @code{$ZROWS} and moves the cursor to the upper-left corner of the screen.

@item @code{?@emph{n}} (position)
Advances the cursor and @code{$X} forward to position @emph{n}.

@end table

@item Single-Character Read (@code{*@emph{variable-name}[@emph{:timeout}]})
Reads one character into variable @emph{variable-name}. If the optional @emph{timeout} is specified, will wait @emph{timeout} seconds to retrieve one character. If a character is read within @emph{timeout} seconds, @code{$TEST} will be set to @emph{1}. If no character is read within @emph{timeout} seconds, @code{$TEST} will be set to @emph{0}.

@item Variable-Length Character Read (@code{@emph{variable-name}[@emph{:timeout}]})
Reads characters into @emph{variable-name} until the character or character pair in @code{^$DEVICE(@emph{io-channel},"OPTIONS","TERMINATOR")} is encountered. If the optional @emph{timeout} is specified, will wait @emph{timeout} seconds to retrieve characters. If characters are read within @emph{timeout} seconds, @code{$TEST} will be set to @emph{1}. If no character is read within @emph{timeout} seconds, @code{$TEST} will be set to @emph{0}.

@item Fixed-Length Character Read (@code{@emph{variable-name}#@emph{count}[@emph{:timeout}]})
Reads @emph{count} characters into @emph{variable-name}. If the optional @emph{timeout} is specified, will wait @emph{timeout} seconds to retrieve characters. If characters are read within @emph{timeout} seconds, @code{$TEST} will be set to @emph{1}. If no character is read within @emph{timeout} seconds, @code{$TEST} will be set to @emph{0}.

@item Control Mnemonic (@code{/@emph{control-mnemonic}[@emph{(arg1[,...argN])}]})
Outputs X3.64 control mnemonic @emph{control-mnemonic} to @code{$IO}. Please see the appendix on X3.64 Control Mnemonics for more information.

@end table

@node SET
@section SET
@cindex SET
@cindex commands, SET

The @code{SET} command places values into one or more variables, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

@emph{Syntax}
@example
SET[@emph{:postcondition}] @emph{set-argument}[=@emph{expression} | @emph{postfix-operator}][@emph{,...set-argument}[=@emph{expression} | @emph{postfix-operator}]]
@end example

Each @emph{set-argument} can be:

@table @asis
@item @emph{variable-name}
A local variable, global variable, writable intrinsic special variable, or writable structured system variable.

@item @emph{lhs-function}
@code{$EXTRACT} or @code{$PIECE}.
@end table

If any grouping of @emph{set-argument}s is surrounded by parentheses, all @emph{set-argument}s in the parenthesized group will be set to the result of @emph{expression}.

If @emph{postfix-operator} is used instead of @code{=@emph{expression}}, the results of applying @emph{postfix-operator} to the @emph{set-argument} will be stored in @emph{set-argument}. @emph{postfix-operator} may not be used following a parenthesized group of @emph{set-argument}s.

@emph{Example (postfix-operator)}

@example
SET A++,B-- ; increments A, decrements B
@end example

@node TCOMMIT
@section TCOMMIT
@cindex TCOMMIT
@cindex commands, TCOMMIT

Commits all pending transactions to the data files, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

@emph{Syntax}
@example
TCOMMIT[@emph{:postcondition}]
@end example

@node THEN
@section THEN
@cindex THEN
@cindex commands, THEN

Saves the value of @code{$TEST} until the end of the current line, restoring it at the end of the current line or when a @code{QUIT} is encountered. @code{THEN} should be used in all new code in conjunction with @code{IF}.

@emph{Example}
@example
IF 1 THEN  WRITE "HELLO!",!
@end example

@node THROW
@section THROW
@cindex THROW
@cindex commands, THROW
@cindex commands, non-standard
@emph{FreeM Extension}

Raises an error condition as long as the optional @emph{postcondition} is @emph{true} or omitted.

@emph{Syntax}

@example
@code{THROW@emph{:postcondition} @emph{expr V error-code}}
@end example

@emph{Example}

@example
@code{THROW "M102"}
@end example

@node TROLLBACK
@section TROLLBACK
@cindex TROLLBACK
@cindex commands, TROLLBACK

Rolls back all pending transactions for the current process, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

@emph{Syntax}

@example
TROLLBACK[@emph{:postcondition}]
@end example

@node TSTART
@section TSTART
@cindex TSTART
@cindex commands, TSTART

Introduces a new transaction level, incrementing @code{$TLEVEL}, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted. Any global data file operations encountered when @code{$TLEVEL} is greater than zero will not be committed to the global data files until @code{TCOMMIT} is encountered.

If a transaction is restartable, variables in the @emph{variables-list} will be restored to their original values on a restart of the transaction.

@emph{Syntax}

@example
TSTART[@emph{:postcondition}] @emph{<variables-list>}:@emph{<transaction-parameters>}
@end example

@emph{<variables-list>} can be:

@table @asis

@item @code{()}
Do not save off any local variables. Makes the transaction non-restartable.

@item @code{*}
Save off all local variables. Makes the transaction restartable.

@item @code{@emph{variableName}}
Saves off only one local variable, @emph{variableName}. Makes the transaction restartable.

@item @code{(@emph{variableName1},...,@emph{variableNameN})}
Saves off all local variables listed. Makes the transaction restartable.

@end table

@emph{<transaction-parameters>} can be:

@table @asis

@item @code{S[ERIAL]}
Forces ACID properties on the transaction. When @code{SERIAL} is not selected, transactions occur in batch mode, and no attempt is made to guarantee ACID properties.

@item @code{T[RANSACTIONID]=@emph{transaction-id}}
Sets the ID of the transaction to @emph{transaction-id}

@end table

If you are using more than one transaction parameter, surround all of them in parentheses and separate them with commas, e.g.:

@example
TSTART (FOO,BAR):(SERIAL,TRANSACTIONID="FOO")
@end example

@node UNMAP
@section UNMAP
@cindex UNMAP
@cindex commands, UNMAP
@cindex commands, implementation-specific
@cindex commands, non-standard

Removes any mapping connecting @emph{gvn} to a non-default namespace, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

@emph{Syntax}

@example
UNMAP GLOBAL @emph{gvn}
@end example

@node USE
@section USE
@cindex USE
@cindex commands, USE

Sets @code{$IO} to a particular FreeM I/O channel, allowing @code{READ}s from and @code{WRITE}s to the associated terminal, sequential file, or network socket. Also sets various device parameters.

@emph{Syntax (Terminal)}

@example
  USE@emph{:postcondition} @emph{io-channel}[:(@emph{right-margin}:@emph{input-field-length}:@emph{device-status-word}:@emph{position}:@emph{line-terminator}:@emph{break-key})]
@end example

For terminals, @emph{io-channel} must be 0.

Semantic and functional description of each device parameter TBA.

@emph{Syntax (Sequential Files)}

@example
  USE@emph{:postcondition} @emph{io-channel}[:@emph{seek-position}:@emph{terminator}:@emph{nodelay})]
@end example

For sequential files, @emph{io-channel} must be in the range 1-99.

Semantic and functional description of each device parameter TBA.

@emph{Syntax (Network Sockets)}

@example
  USE@emph{:postcondition} @emph{io-channel}
@end example

The above syntax will set @code{$IO} to @emph{io-channel}, directing successive @code{READ}s and @code{WRITE}s to @emph{io-channel}, provided the optional @emph{postcondition} is @emph{true} or omitted.

@example
  USE@emph{:postcondition} @emph{io-channel}:/CONNECT
@end example

The above syntax will set @code{$IO} to @emph{io-channel}, as in the prior example, but will also attempt to connect to the host and port specified for @emph{io-channel} when it was @code{OPEN}ed. The @code{/CONNECT} control mnemonic is only valid for socket channels whose connection type is @code{TCP}. Using @code{/CONNECT} on a @code{UDP} socket channel will throw @code{SCKAERR} (error code 55).

For network sockets, @emph{io-channel} must be in the range 100-255.

@node VIEW
@section VIEW
@cindex VIEW
@cindex commands, VIEW

Provides write access to various FreeM internal parameters, provided the optional @emph{postcondition} evaluates to @emph{true} or is omitted.

@emph{Syntax}
@example
VIEW[@emph{:postcondition}] @emph{view-number}[:@emph{view-argument}[:@emph{view-argument}...]]
@end example

The @emph{view-number} argument can be one of the following:

@table @asis

@item @code{21} - Close All Globals
Closes all global data files open in the current process. Takes no arguments.

@emph{Syntax}
@example
VIEW 21
@end example

@item @code{29} - Symbol Table Copy
Copies the primary symbol table's contents to the alternate symbol table. Takes no arguments.

@emph{Syntax}
@example
VIEW 29
@end example

@item @code{52} - Set G0 Input Translation Table for @code{$IO}

@emph{Syntax}
@example
VIEW 52:@emph{expr V trantab}
@end example

@item @code{53} - Set G0 Output Translation Table for @code{$IO}

@emph{Syntax}
@example
VIEW 53:@emph{expr V trantab}
@end example

@item @code{54} - Set G1 Input Translation Table for @code{$IO}

@emph{Syntax}
@example
VIEW 54:@emph{expr V trantab}
@end example

@item @code{55} - Set G1 Output Translation Table for @code{$IO}

@emph{Syntax}
@example
VIEW 55:@emph{expr V trantab}
@end example

@item @code{62} - Set @code{$RANDOM} Seed Number
Sets the seed number used by @code{$RANDOM} to @emph{numexpr}.

@emph{Syntax}
@example
VIEW 62:@emph{numexpr}
@end example

@item @code{63} - Set @code{$RANDOM} Parameter A
Sets the number used for @code{$RANDOM} Parameter A to @emph{numexpr}.

@emph{Syntax}
@example
VIEW 63:@emph{numexpr}
@end example

@item @code{64} - Set @code{$RANDOM} Parameter B
Sets the number used for @code{$RANDOM} Parameter B to @emph{numexpr}.

@emph{Syntax}
@example
VIEW 64:@emph{numexpr}
@end example

@item @code{65} - Set @code{$RANDOM} Parameter C
Sets the number used for @code{$RANDOM} Parameter C to @emph{numexpr}.

@emph{Syntax}
@example
VIEW 65:@emph{numexpr}
@end example

@item @code{66} - Set or Clear @code{SIGTERM} Handling Flag
Enables or disables handling of @code{SIGTERM} UNIX signals. If @emph{tvexpr} evaluates to 1 (@emph{true}), @code{SIGTERM} handling will be enabled. Otherwise, @code{SIGTERM} handling will be disabled.

@emph{Syntax}
@example
VIEW 66:@emph{tvexpr}
@end example

@item @code{67} - Set or Clear @code{SIGHUP} Handling Flag
Enables or disables handling of @code{SIGHUP} UNIX signals. If @emph{tvexpr} evaluates to 1 (@emph{true}), @code{SIGHUP} handling will be enabled. Otherwise, @code{SIGHUP} handling will be disabled.

@emph{Syntax}
@example
VIEW 67:@emph{tvexpr}
@end example

@item @code{70} - Set @code{$ZSORT}/@code{$ZSYNTAX} Flag
Selects whether @code{$ZS} resolves to @code{$ZSORT} or @code{$ZSYNTAX}.

If @emph{tvexpr} evaluates to @emph{true}, selects @code{$ZSYNTAX}. Otherwise, selects @code{$ZSORT}.

@emph{Syntax}
@example
VIEW 70:@emph{tvexpr}
@end example

@item @code{71} - Set @code{$ZNEXT}/@code{$ZNAME} Flag
Selects whether @code{$ZN} resolves to @code{$ZNEXT} or @code{$ZNAME}.

If @emph{tvexpr} evaluates to @emph{true}, selects @code{$ZNAME}. Otherwise, selects @code{$ZNEXT}.

@emph{Syntax}
@example
VIEW 71:@emph{tvexpr}
@end example

@item @code{72} - Set @code{$ZPREVIOUS}/@code{$ZPIECE} Flag
Selects whether @code{$ZP} resolves to @code{$ZPREVIOUS} or @code{$ZPIECE}.

If @emph{tvexpr} evaluates to @emph{true}, selects @code{$ZPIECE}. Otherwise, selects @code{$ZPREVIOUS}.

@emph{Syntax}
@example
VIEW 72:@emph{tvexpr}
@end example

@item @code{73} - Set @code{$ZDATA}/@code{$ZDATE} Flag
Selects whether @code{$ZD} resolves to @code{$ZDATA} or @code{$ZDATE}.

If @emph{tvexpr} evaluates to @emph{true}, selects @code{$ZDATE}. Otherwise, selects @code{$ZDATA}.

@emph{Syntax}
@example
VIEW 73:@emph{tvexpr}
@end example

@item @code{79} - Set Old @code{ZJOB} vs. New @code{ZJOB} Flag
If @emph{tvexpr} evaluates to @emph{true}, sets the @code{ZJOB} mode to new, otherwise, sets it to old.

@emph{Syntax}
@example
VIEW 79:@emph{tvexpr}
@end example

@item @code{80} - Set or Clear 8-Bit Flag
If @emph{tvexpr} evaluates to @emph{true}, sets FreeM to 8-bit mode. Otherwise, sets FreeM to 7-bit mode.

@emph{Syntax}
@example
VIEW 80:@emph{tvexpr}
@end example

@item @code{81} - Set or Clear PF1 Flag
If @emph{tvexpr} evaluates to @emph{true}, sets the @code{PF1} flag. We do not yet know what this does.

@emph{Syntax}
@example
VIEW 81:@emph{tvexpr}
@end example

@item @code{83} - Set or Clear Text in @code{$ZERROR} Flag
If @emph{tvexpr} evaluates to @emph{true}, descriptive error messages will be included in @code{$ZERROR}. Otherwise, only the short error code (i.e. @emph{ZILLFUN}) will be included in @code{$ZERROR}.

@emph{Syntax}
@example
VIEW 83:@emph{tvexpr}
@end example

@item @code{87} - Date Type Definition
We believe this defines date formats for @code{$ZDATE}, but we have not yet figured out how it works.

@emph{Syntax}
@example
; Syntax unknown
@end example

@item @code{88} - Time Type Definition
We believe this defines time formats for @code{$ZTIME}, but we have not yet figured out how it works.

@emph{Syntax}
@example
; Syntax unknown
@end example

@item @code{91} - Set Default Expression for Missing @code{QUIT} Expression
Sets the default expression to be printed when a @code{QUIT} is encountered where a @code{QUIT} argument would be expected, but was not provided. We're not entirely sure what this does.

@emph{Syntax}
@example
; Syntax unknown
@end example

@item @code{92} - Set Type Mismatch Error Flag on @code{EUR2DEM}
If @emph{tvexpr} evaluates to @emph{true}, a type mismatch error will be thrown in @code{EUR2DEM} currency conversions in certain situations that we do not yet understand.

@emph{Syntax}
@example
VIEW 92:@emph{tvexpr}
@end example

@item @code{93} - Define @code{ZKEY} Production Rule
We do not know what this does.

@item @code{96} - Set Global Prefix
Forces global data filenames to be prefixed with the result of @emph{expr}.

@emph{Syntax}
@example
VIEW 96:@emph{expr V string}
@end example

@item @code{97} - Set Global Postfix
Forces global data filenames to be postfixed with the result of @emph{expr}.

@emph{Syntax}
@example
VIEW 97:@emph{expr V string}
@end example

@item @code{98} - Set Routine Extension
Sets the default extension for M routine filenames to the result of @emph{expr}.

@emph{Syntax}
@example
VIEW 98:@emph{expr V string}
@end example

@item @code{101} - Set @code{ierr}
Sets the FreeM internal @code{ierr} value to @emph{intexpr}. Used by some FreeM polyfills (commands or functions implemented in M code).

@emph{Syntax}
@example
VIEW 101:@emph{intexpr}
@end example

@item @code{102} - Set @code{ierr} (Deferred)
Sets the FreeM internal @code{ierr} value to @emph{intexpr}, but only after the current process stack level is exited. Used by FreeM polyfills to throw an error that will appear to come from the user's own code rather than the polyfill implementation M code.

@emph{Syntax}
@example
VIEW 102:@emph{intexpr}
@end example

@item @code{103} - Signal @code{MERGE} to @code{^$WINDOW} Complete
Signals FreeM's MWAPI implementation that a @code{MERGE} to @code{^$WINDOW} or descendant subscripts thereof has completed.

@emph{Syntax}
@example
VIEW 103[@emph{:subscript}]
@end example

@item @code{110} - Set Local @code{$ORDER}/@code{$QUERY} Data Value
Sets the local variable @code{$ORDER}/@code{$QUERY} data value to the result of @emph{expr}. We're not entirely sure what this is.

@emph{Syntax}
@example
VIEW 110:@emph{expr}
@end example

@item @code{111} - Set Global @code{$ORDER}/@code{$QUERY} Data Value
Sets the global variable @code{$ORDER}/@code{$QUERY} data value to the result of @emph{expr}. We're not entirely sure what this is.

@emph{Syntax}
@example
VIEW 111:@emph{expr}
@end example

@item @code{113} - Set @code{termio} Information
We don't know what this does.

@item @code{133} - Remember @code{ZLOAD} Directory on @code{ZSAVE}
We don't know what this does, but it takes a @emph{tvexpr}.

@emph{Syntax}
@example
VIEW 133:@emph{tvexpr}
@end example

@end table

@node WATCH
@section WATCH
@cindex WATCH
@cindex commands, WATCH
@cindex commands, debugging
@cindex commands, implementation-specific
@cindex commands, non-standard
@emph{FreeM Extension}

Sets a watchpoint on a global, local, or SSVN node.

@emph{Syntax}


In its @emph{argumentless} form, @code{WATCH} toggles watchpoints on and off, provided the optional @emph{postcondition} is @emph{true} or omitted.

@example
WATCH[@emph{:postcondition}]
@end example

In its @emph{inclusive} form, @code{WATCH} adds, removes, or examines watchpoints, provided the optional @emph{postcondition} is @emph{true} or omitted.

A @code{+} adds a new watchpoint to the following variable.

A @code{-} removes an existing watchpoint for the following variable.

A @code{?} examines the status of a watchpoint for the following variable.

@example
WATCH[@emph{:postcondition}] [+|-|?]@emph{var1}...,[+|-|?]@emph{varN}
@end example


The following example demonstrates turning watchpoint processing on and adding a watchpoint for global variable @code{^jpw(1)}. It then changes the value of @code{^jpw(1)}.

@example
USER> WATCH
 
Watchpoints enabled.
 
USER> WATCH +^JPW(1)
 
Added '^JPW("1")' to the watchlist.
 
USER> SET ^JPW(1)="new value"
 
>> WATCHPOINT:  ^JPW("1") => 'new value' (changed 1 times)

@end example

The following example will remove that watchpoint:

@example
USER> WATCH -^JPW(1)
 
Removed '^JPW("1")' from the watchlist.
 
USER> WATCH ?^JPW(1)
 
'^JPW("1")' is not being watched.
@end example

@node WITH
@section WITH
@cindex WITH
@cindex commands, WITH
@cindex commands, non-standard
@emph{FreeM Extension}

Sets a prefix to be applied to all subsequent local variable or constant references.

@emph{Syntax}

@example
@code{WITH@emph{:postcondition} @emph{var-prefix}}
@end example

In the above single-argument form, sets the @code{$WITH} prefix to @emph{var-prefix}, provided that the optional @emph{postcondition} is either @emph{true} or omitted.

The @emph{var-prefix} argument may be a string literal or any valid FreeM expression.

@example
@code{WITH@emph{:postcondition}}
@end example

In the above argumentless form, clears the @code{$WITH} prefix, provided the optional @emph{postcondition} is either @emph{true} or omitted. Equivalent to @code{WITH ""}.


@node WRITE
@section WRITE
@cindex WRITE
@cindex commands, WRITE

@node XECUTE
@section XECUTE
@cindex XECUTE
@cindex commands, XECUTE

@node ZALLOCATE
@section ZALLOCATE
@cindex ZALLOCATE
@cindex commands, ZALLOCATE
@cindex commands, implementation-specific
@cindex commands, non-standard
@emph{FreeM Extension}

@node ZBREAK
@section ZBREAK
@cindex ZBREAK
@cindex commands, ZBREAK
@cindex commands, debugging
@cindex commands, implementation-specific
@cindex commands, non-standard
@emph{FreeM Extension}

@node ZDEALLOCATE
@section ZDEALLOCATE
@cindex ZDEALLOCATE
@cindex commands, ZDEALLOCATE
@cindex commands, implementation-specific
@cindex commands, non-standard
@emph{FreeM Extension}

@node ZGO
@section ZGO
@cindex ZGO
@cindex commands, ZGO
@cindex commands, implementation-specific
@cindex commands, non-standard
@emph{FreeM Extension}

@node ZHALT
@section ZHALT
@cindex ZHALT
@cindex commands, ZHALT
@cindex commands, implementation-specific
@cindex commands, non-standard
@emph{FreeM Extension}

@node ZINSERT
@section ZINSERT
@cindex ZINSERT
@cindex commands, ZINSERT
@cindex commands, implementation-specific
@cindex commands, non-standard
@emph{FreeM Extension}

@node ZJOB
@section ZJOB
@cindex ZJOB
@cindex commands, ZJOB
@cindex commands, implementation-specific
@cindex commands, non-standard
@emph{FreeM Extension}

When @code{ZJOB} is used, the semantics are identical to @code{JOB}, with the exception that the @emph{timeout} is forced to be @code{0}, regardless of what the user specifies.

For more information, see @code{JOB}.

@node ZLOAD
@section ZLOAD
@cindex ZLOAD
@cindex commands, ZLOAD
@cindex commands, implementation-specific
@cindex commands, non-standard
@emph{FreeM Extension}

Loads routine @emph{<routine-name>} into FreeM's routine buffer, provided the optional @emph{postcondition} is @emph{true} or omitted.

@emph{Syntax}

@example
ZLOAD@emph{:postcondition} @emph{<routine-name>}
@end example

@node ZNEW
@section ZNEW
@cindex ZNEW
@cindex commands, ZNEW
@cindex commands, implementation-specific
@cindex commands, non-standard
@emph{FreeM Extension}

@node ZPRINT
@section ZPRINT
@cindex ZPRINT
@cindex commands, ZPRINT
@cindex commands, implementation-specific
@cindex commands, non-standard
@emph{FreeM Extension}

Prints the contents of the current routine buffer, provided the optional @emph{postcondition} is @emph{true} or omitted.

@emph{Syntax}

@example
ZPRINT@emph{:postcondition}
@end example

@node ZQUIT
@section ZQUIT
@cindex ZQUIT
@cindex commands, ZQUIT
@cindex commands, implementation-specific
@cindex commands, non-standard
@emph{FreeM Extension}

In its single-argument form, quits from @emph{levels} levels of the stack, provided the optional @emph{postcondition} is @emph{true} or omitted.

In its argumentless form, quits from @code{$STACK} levels of the stack, provided the optional @emph{postcondition} is @emph{true} or omitted.

@emph{Syntax}

@example
@code{ZQUIT@emph{:postcondition} [@emph{levels}]}
@end example

@node ZREMOVE
@section ZREMOVE
@cindex ZREMOVE
@cindex commands, ZREMOVE
@cindex commands, implementation-specific
@cindex commands, non-standard
@emph{FreeM Extension}

@node ZSAVE
@section ZSAVE
@cindex ZSAVE
@cindex commands, ZSAVE
@cindex commands, implementation-specific
@cindex commands, non-standard
@emph{FreeM Extension}

@node ZTRAP
@section ZTRAP
@cindex ZTRAP
@cindex commands, ZTRAP
@cindex commands, debugging
@cindex commands, implementation-specific
@cindex commands, non-standard
@emph{FreeM Extension}

@node ZWRITE
@section ZWRITE
@cindex ZWRITE
@cindex commands, ZWRITE
@cindex commands, implementation-specific
@cindex commands, non-standard
@emph{FreeM Extension}

Writes the names and values of M variables to @code{$IO}.

@emph{Syntax}

@example
ZWRITE@emph{:postcondition}
@end example

In the argumentless form, writes the names and values of all local variables to @code{$IO} if the optional @emph{postcondition} is @emph{true} or omitted.

@example
ZWRITE@emph{:postcondition} @emph{ArrayName},@dots{}
@end example

In the inclusive form, writes the names and values of all local, global, or structured system variables specified in the list of @emph{ArrayName}s to @code{$IO} if the optional @emph{postcondition} is @emph{true} or omitted.

@example
ZWRITE@emph{:postcondition} (@emph{ArrayName},@dots{})
@end example

In the exclusive form, writes all local variables @emph{except} those specified in the list of @emph{ArrayName}s to @code{$IO} if the optional @emph{postcondition} is @emph{true} or omitted.


@node Structured System Variables
@chapter Structured System Variables
@cindex variables, structured system
@cindex structured system variables
@cindex SSVNs

@menu
* ^$CHARACTER::                         Character set information.
* ^$DEVICE::                            Device information.
* ^$DISPLAY::                           Information about graphic display.
* ^$EVENT::                             Information supplied about a synchronous or asynchronous event.
* ^$GLOBAL::                            Information about M globals.
* ^$JOB::                               Information about and control of FreeM jobs.
* ^$LOCK::                              Information about the FreeM lock table.
* ^$OBJECT::                            Information about FreeM objects.
* ^$ROUTINE::                           Information about FreeM routines.
* ^$SYSTEM::                            Information about the running system.
* ^$WINDOW::                            Configuration of MWAPI windows.
* ^$ZPROCESS::                          Information about and control of system processes.
* ^$ZRPI::                              Information about and control of Raspberry Pi GPIO pins.
@end menu

SSVN subscripts are each described in the following format:

@table @asis
@item @code{@emph{<ssvn-subscript-name>}} +/-R +/-U +/-D
@end table

The R, U, and D flags represent Read, Update, and Delete. A minus sign indicates that the given operation is @emph{not} allowed, and a plus sign indicates that the given operation @emph{is} allowed.

@node ^$CHARACTER
@section ^$CHARACTER
@cindex ^$CHARACTER
@cindex structured system variables, ^$CHARACTER

Exposes character set information. As FreeM currently only supports the @code{M} character set, the first subscript of @code{^$CHARACTER} must always be @code{"M"}.

The following values for the second subscript are supported:

@table @asis

@item @code{IDENT} +R -U -D
Returns the empty string.

@item @code{COLLATE} +R -U -D
Returns the empty string.

@item @code{INPUT} +R -U -D
Returns the empty string if the third subscript is @code{M}, otherwise, raises error @code{M38}.

@item @code{OUTPUT} +R -U -D
Returns the empty string if the third subscript is @code{M}, otherwise, raises error @code{M38}.

@end table

@node ^$DEVICE
@section ^$DEVICE
@cindex ^$DEVICE
@cindex structured system variables, ^$DEVICE

FreeM implements several important pieces of functionality in the @code{^$DEVICE} SSVN.

The first subscript of @code{^$DEVICE} represents the I/O channel of an @code{OPEN}ed device.

The following values for the second subscript are supported:

@table @asis

@item @code{$DEVICE}
Returns the value of @code{$DEVICE} for the specified I/O channel.

@item @code{$X} +R -U -D
Returns the horizontal cursor position of a terminal device. Only valid if the I/O channel is @code{0}.

@item @code{$Y} +R -U -D
Returns the vertical cursor position of a terminal device. Only valid if the I/O channel is @code{0}.

@item @code{ROWS} +R -U -D
Returns the number of character rows on the terminal device. Only valid if the I/O channel is @code{0}.

@item @code{COLUMNS} +R -U -D
Returns the number of character columns on the terminal device. Only valid if the I/O channel is @code{0}.

@item @code{CHARACTER} +R -U -D
Returns the character set of the specified I/O channel; always @code{M} in the current implementation.

@item @code{INPUT_BUFFER} +R +U -D
Returns or sets the contents of the input buffer for the specified I/O channel. Data populated in this node will remain in the buffer until subsequent @code{READ} command(s) remove it. This can be used to perform input buffer stuffing, i.e., to fill out an interactive form programmatically.

@item @code{NAME} +R -U -D
Returns the operating system's name for the file, device, or socket attached to the specified I/O channel.

@item @code{FD} +R -U -D
Returns the UNIX file descriptor of the specified I/O channel.

@item @code{MODE} +R -U -D
Returns one of @code{READ}, @code{WRITE}, @code{READWRITE}, or @code{APPEND}, depending on the mode in which the specified I/O channel was opened.

@item @code{EOF} +R -U -D
Returns @code{1} if the I/O channel has encountered an end-of-file condition; @code{0} otherwise. Only valid if the I/O channel is connected to a sequential file.

@item @code{LENGTH} +R -U -D
Returns the length of the file connected to the I/O channel. Only valid if the I/O channel is connected to a sequential file.

@item @code{NAMESPACE} +R -U -D
Returns the current @emph{mnemonic-space} in use for the referenced I/O channel. Always @code{X364} for terminals and blank for sequential files.

@item @code{TYPE} +R -U -D
Returns either @code{1,FILE}, @code{2,SOCKET}, or @code{4,TERMINAL}, depending on the device type associated with the specified I/O channel.

@item @code{OPTIONS} -R -U -D
The following subscripts reside beneath @code{^$DEVICE(<io-channel>,"OPTIONS")}, and this subscript may not be accessed without one of the following third-level subscripts being specified:

@table @asis

@item @code{DSW} +R +U -D
Sets or returns the current @emph{Device Status Word} controlling terminal characteristics. Only valid for I/O channel 0.

@item @code{TERMINATOR} +R +U -D
Sets or returns the @code{READ} terminator for the specified I/O channel. Must be either @code{$C(13,10)} or @code{$C(10)}. Currently only supported for socket devices (those having an I/O channel of 100-255).

@item @code{TERMID} +R -U -D
Returns the type of terminal connected to channel 0. Only valid for I/O channel 0.

@item @code{ECHO} +R +U -D
Enables or disables local echo of characters typed in a @code{READ} command. Only valid for I/O channel 0. Corresponds to bit 0 of the Device Status Word.

@item @code{DELMODE} +R +U -D
Enables or disables visual backspace during a @code{READ} command. Only valid for I/O channel 0. Corresponds to bit 2 of the Device Status Word.

@item @code{ESCAPE} +R +U -D
Enables or disables escape sequence processing during a @code{READ} command. Only valid for I/O channel 0. Corresponds to bit 6 of the Device Status Word.

@item @code{CONVUPPER} +R +U -D
Enables or disables automatic conversion to uppercase of alphabetical characters during a @code{READ} command. Only valid for I/O channel 0. Corresponds to bit 14 of the Device Status Word.

@item @code{DELEMPTY} +R +U -D
Enables or disables the automatic deletion of empty strings supplied to a @code{READ} command. Only valid for I/O channel 0. Corresponds to bit 19 of the Device Status Word.

@item @code{NOCTRLS} +R +U -D
TBD. Only valid for I/O channel 0. Corresponds to bit 20 of the Device Status Word.

@item @code{CTRLOPROC} +R +U -D
Enables or disables @emph{Ctrl-O} processing during @code{READ} commands. Only valid for I/O channel 0. Corresponds to bit 21 of the Device Status Word.

@item @code{NOTYPEAHEAD} +R +U -D
Enables or disables typeahead buffering during @code{READ} commands. Only valid for I/O channel 0. Corresponds to bit 25 of the Device Status Word.
@end table
@end table

@emph{Example}

The following example M code opens @code{/etc/freem.conf} and reads its contents line-by-line until the end of the file is reached.

@example
 SET ^$JOB($JOB,"IOPATH")="/etc"   ; set I/O path to /etc
 OPEN 1:"freem.conf/r" ; open freem.conf for reading
 ;
 ; read until we run out of lines
 ;
 FOR  USE 1 READ LINE USE 0 QUIT:^$DEVICE(1,"EOF")  D
 . WRITE LINE,!
 ;
 CLOSE 1
 QUIT
@end example

@node ^$DISPLAY
@section ^$DISPLAY
@cindex ^$DISPLAY
@cindex structured system variables, ^$DISPLAY

Provides information about the specified graphical display. The first subscript corresponds to a display number, which is an integer value, often corresponding to the current value of the @code{$PDISPLAY} ISV.

The following second-level subscripts and specified descendant subscripts are supported:

@table @asis

@item @code{CLIPBOARD} +R +U +D
Retrieves, sets, or erases the contents of the system clipboard.

@item @code{PLATFORM} +R -U -D
Retrieves the name and version of the underlying window system platform.

@item @code{SIZE} +R -U -D
Retrieves the display resolution of the specified graphical display. For instance, a 1080p display would have a @code{SIZE} value of @code{1920,1080}.

@item @code{SPECTRUM} +R -U -D
Retrieves the color depth (number of colors supported) of the specified graphical display.

@item @code{COLORTYPE} +R -U -D
Always returns @code{COLOR}, as monochrome and grayscale displays are not yet supported in FreeM.

@item @code{UNITS} +R -U -D
Returns the measurement unit of the specified display, i.e., @code{PIXEL}.

@item @code{TYPEFACE} +R -U -D
The third-level subscripts beneath this subscript represent a list of font families available on this display. The fourth level subscript is a list of sizes supported for the specified typeface, or @code{0} for vector typefaces, such as TrueType, OpenType, and Adobe Type 1 fonts.

@end table

@node ^$EVENT
@section ^$EVENT
@cindex ^$EVENT
@cindex structured system variables, ^$EVENT

The @code{^$EVENT} SSVN is not yet implemented.

@node ^$GLOBAL
@section ^$GLOBAL
@cindex ^$GLOBAL
@cindex structured system variables, ^$GLOBAL

The @code{^$GLOBAL} structured system variable provides information about M globals. The first-level subscript is a global name, sans the leading caret symbol.

The following second-level subscripts are supported:

@table @asis

@item @code{BYTES} +R -U -D
Returns the number of bytes this global occupies in fixed storage.

@item @code{BLOCKS} +R -U -D
Returns the number of blocks contained in this global.

@item @code{BLOCKSIZE} +R -U -D
Returns the size of data blocks for this global. Currently, FreeM only supports 1024-byte blocks.

@item @code{FILE} +R -U -D
Returns the full filesystem path to the data file where this global resides in fixed storage.

@item @code{NAMESPACE} +R +U +D
Returns or sets the name of the FreeM namespace to which this global belongs. @code{SET}ting this node creates a mapping for the specified global name to a non-default namespace. @code{KILL}ing this node restores the mapping configuration for the specified global to the default.

@end table

@node ^$JOB
@section ^$JOB
@cindex ^$JOB
@cindex structured system variables, ^$JOB

FreeM fully implements @code{^$JOB} per ANSI X11.1-1995, as well as several extensions proposed in the M Millennium Draft Standard.

The first subscript of @code{^$JOB} represents the @code{$JOB} of the process.

If you @code{KILL} a first-level subscript of @code{^$JOB}, the @code{SIGTERM} signal will be sent to the corresponding UNIX process, causing pending transactions to be rolled back and the process to be terminated. If the targeted process is in direct mode, the user will be prompted with options of either rolling back or committing any pending transactions.

The following subscripts are supported:

@table @asis

@item @code{GVNDEFAULT} +R +U +D
Contains a default expression to be evaluated if a global variable access attempt results in an @code{M7} error.

Equivalent to wrapping all global accesses in @code{$GET(@emph{global-name},@emph{string-expr})}.

@item @code{LVNDEFAULT} +R +U +D
Contains a default expression to be evaluated if a local variable access attempt results in an @code{M6} error.

Equivalent to wrapping all local accesses in @code{$GET(@emph{global-name},@emph{string-expr})}.

@item @code{LVNQOVAL} +R +U +D
Contains the data value (if any) at the subscripted local variable reference from the most recent @code{$ORDER} or @code{$QUERY} operation.

This node is useful for code that uses @code{$ORDER} or @code{$QUERY} heavily in loops that retrieve successive data values, as it will prevent an additional symbol table scan that would result from retrieving the data value in the usual way, thus improving application performance. However, this optimization comes at the cost of compatibility with other M implementations.

@item @code{GVNQOVAL} +R +U +D
Contains the data value (if any) at the subscripted global variable reference from the most recent @code{$ORDER} or @code{$QUERY} operation.

This node is useful for code that uses @code{$ORDER} or @code{$QUERY} heavily in loops that retrieve successive data values, as it will prevent an additional data file scan that would result from retrieving the data value in the usual way, thus improving application performance. However, this optimization comes at the cost of compatibility with other M implementations.

@item @code{ZCOMMANDS} +R +U -D
Contains a space-delimited list of @code{Z}-commands to be treated as intrinsic. Any @code{Z}-command not appearing in this list will be treated as a user-defined command.

For instance, if command @code{ZFOO} does @emph{not} appear in this list, FreeM will attempt to run @code{^%ZFOO} as a subroutine when the @code{ZFOO} command is encountered in program code.

If you remove a command from this list, you may provide your own private M implementation of the command in the manner described above.

If an argument is passed to a @code{Z}-command you implement in M, it is made available to your M code in a variable whose name is specified in @code{^$JOB($JOB,"ZCOMMAND_ARGUMENT_NAME")}, which defaults to @code{%}.

@item @code{PIPE_GLVN} +R +U -D
Contains an M local or global variable to be used as standard input or standard output for the external shell commands run by @code{!<} and @code{!>}.

@item @code{ZCOMMAND_ARGUMENT_NAME} +R +U -D
Returns or sets the variable name in which arguments to user-defined @code{Z}-commands are passed. Defaults to @code{%}.

@item @code{ZFUNCTIONS} +R +U -D
Contains a space-delimited list of @code{Z} functions to be treated as intrinsic. Any @code{Z} function not appearing in this list will be treated as a user-defined extrinsic function.

For instance, if function @code{$ZFOO} does @emph{not} appear in this list, FreeM will attempt to return the value of @code{$$^%ZFOO} called as an extrinsic function.

If you remove a function from this list, you may provide your own private M implementation of the function in the manner described above.

@item @code{ZSVS} +R +U -D
Contains a space-delimited list of @code{Z} special variables to be treated as intrinsic. Any @code{Z} special variable  not appearing in this list will be treated as a user-defined extrinsic function taking no arguments.

For instance, if the special variable @code{$ZFOO} does @emph{not} appear in this list, FreeM will attempt to return the value of @code{$$^%ZFOO} called as an extrinsic function.

If you remove a built-in special variable from this list, you may provide your own private M implementation of the special variable in the manner described above.

@item @code{BREAK_HANDLER} +R +U -D
Contains M code to be executed when the @code{BREAK} command is run.

@item @code{ROUTINE_BUFFER_SIZE} +R +U -D
Returns or sets the number of bytes allocated to each routine buffer. If @code{ROUTINE_BUFFER_AUTO_ADJUST} is set to @code{0}, this determines the maximum size of routines that FreeM will execute.

@item @code{ROUTINE_BUFFER_COUNT} +R +U -D
Returns or sets the number of routine buffers that FreeM will store in memory concurrently. Raising this value will increase memory usage, but will also increase performance if your applications call many different routines repeatedly.

@item @code{ROUTINE_BUFFER_AUTO_ADJUST} +R +U -D
Determines whether or not the size of routine buffers will be automatically adjusted at runtime. If set to @code{0}, routine buffers will be fixed to the byte size specified in @code{ROUTINE_BUFFER_SIZE} and may be manually resized using @code{ROUTINE_BUFFER_SIZE}. If set to @code{1}, routine buffers will grow automatically as necessary.

@item @code{SYMBOL_TABLE_SIZE} +R +U -D
Returns or sets the number of bytes allocated to each of the two FreeM symbol tables. If @code{SYMBOL_TABLE_AUTO_ADJUST} is @code{1}, this value is treated as a default, initial size. If @code{SYMBOL_TABLE_AUTO_ADJUST} is @code{0}, this value controls the fixed size of the two symbol tables.

@item @code{SYMBOL_TABLE_AUTO_ADJUST} +R +U -D
Determines whether or not the size of the two FreeM symbol tables will be automatically adjusted at runtime. If set to @code{0}, the symbol table will be fixed to the byte size specified in @code{SYMBOL_TABLE_SIZE} and may be manually resized by modifying @code{SYMBOL_TABLE_SIZE}. If set to @code{1}, the two symbol tables will grow automatically as necessary.


@item @code{USER_DEFINED_ISV_TABLE_SIZE} +R +U -D
Returns or sets the number of bytes allocated to the FreeM user-defined intrinsic special variable table. If @code{USER_DEFINED_ISV_TABLE_AUTO_ADJUST} is @code{1}, this value is treated as a default, initial size. If @code{USER_DEFINED_ISV_TABLE_AUTO_ADJUST} is @code{0}, this value controls the fixed byte size of the user-defined intrinsic special variable table.

@item @code{USER_DEFINED_ISV_TABLE_AUTO_ADJUST} +R +U -D
Determines whether or not the size of the FreeM user-defined intrinsic special variable table will be automatically adjusted at runtime. If set to @code{0}, the user-defined ISV table will be fixed to the byte size specified in @code{USER_DEFINED_ISV_TABLE_SIZE} and may be manually resized by modifying @code{USER_DEFINED_ISV_TABLE_SIZE}. If set to @code{1}, the user-defined ISV table will grow automatically as necessary.

@item @code{GVN_UNIQUE_CHARS} +R +U -D
Returns or sets the number of characters of a global name that make it unique, from 1 to 255.

@item @code{GVN_CASE_SENSITIVE} +R +U -D
Returns or sets the case sensitivity of global names. If set to @code{0}, global names are case-insensitive. If set to @code{1}, global names are case-sensitive.

@item @code{GVN_NAME_SUB_LENGTH} +R +U -D
Returns or sets the maximum number of characters of a global name plus all of its subscripts, from 1-255.

@item @code{GVN_SUB_LENGTH} +R +U -D
Returns or sets the maximum number of characters of a single global subscript, from 1-255.

@item @code{SINGLE_USER} +R +U -D
If set to @code{1}, FreeM will skip all file locking operations on globals, as well as the @code{LOCK} and @code{ZALLOCATE} tables. If set to @code{0}, FreeM will enforce file locking on both.

Setting @code{SINGLE_USER} to @code{1} will improve FreeM performance, but you must @emph{ONLY} use this on systems where you are absolutely sure that only one FreeM process will run at any given time, as running multiple instances of FreeM concurrently when any of them are set to @code{SINGLE_USER} mode @emph{will} cause global data and @code{LOCK}/@code{ZALLOCATE} table corruption!

@item @code{CHARACTER} +R -U -D
Returns the character set of the job.

@item @code{CWD} +R +U -D
Returns or sets the current working directory of the job.

@item @code{OPEN} +R -U -D
The @code{^$JOB($JOB,"OPEN",<channel>} subscripts list the open I/O channels in the specified job.

@item @code{ENGINES} +R -U -D
Returns or sets the storage engines for various FreeM subsystems.

The following table lists the types of storage engines that can be defined.

@table @asis

@item @code{GLOBAL} +R +U -D
Returns or sets the global handler for a particular FreeM namespace:

The following code would set the global handler for the @code{SYSTEM} namespace to @code{BERKELEYDB}:

@code{SET ^$JOB($JOB,"ENGINES","GLOBAL","SYSTEM")="BERKELEYDB"}

@item @code{LOCAL} +R -U -D
Returns the local handler for a particular FreeM namespace. Always @code{BUILTIN} in the current FreeM release.

@end table

@item @code{BERKELEYDB,FLUSH_THRESHOLD} +R +U -D
Returns or sets the number of write operations that will be cached in the BerkeleyDB global handler prior to flushing BerkeleyDB's cache to disk.

@item @code{EVENT} +R +U +D
The subtree contained under @code{^$JOB($J,"EVENT")} defines asynchronous event handlers for the current job. Please see @emph{Asynchronous Event Handling} for more information.

@item @code{GLOBAL} +R -U -D
Returns the global environment of the job.

@item @code{IOPATH} +R +U -D
Returns or sets the @emph{I/O path} to be used by the @code{OPEN} command.

@item @code{PRIORITY} +R +U -D
Returns or sets the @emph{nice} value of the FreeM job.

@item @code{REVSTR} +R +U -D
When set to 1, allows @code{$EXTRACT} to accept negative values.

@item @code{ROUTINE} +R -U -D
Returns the name of the routine currently being executed by the job.

@item @code{SYMTAB} +R +U -D
Returns or sets the current local variable symbol table in use.

FreeM supports two unique and independent symbol tables, allowing FreeM programs to maintain two independent sets of identically- or differently-named local variables per process.

The default symbol table is @code{0}, and the alternate symbol table is @code{1}, corresponding to the valid values for @code{^$JOB($JOB,"SYMTAB")}.

Setting this subscript to values other than @code{0} or @code{1} will result in a @code{ZINVEXPR} error.

@item @code{$PDISPLAY} +R -U -D
Returns the value of @code{$PDISPLAY} for the job.

@item @code{$PRINCIPAL} +R -U -D
Returns the value of @code{$PRINCIPAL} for the job.

@item @code{$TLEVEL} +R -U -D
Returns the current transaction level (value of @code{$TLEVEL} for the job.

@item @code{$IO} +R -U -D
Returns the current value of @code{$IO} for the job.

@item @code{USER} +R -U -D
Returns the UID of the user owning the job.

@item @code{GROUP} +R -U -D
Returns the GID of the group owning the job.

@item @code{NAMESPACE} +R +U -D
Returns or sets the name of the job's currently-active namespace.

@item @code{MATH} +R +U -D
Returns or sets the mode in which decimal comparisons and arithmetic calculations are conducted. Valid values are @code{FIXED}, for fixed-point decimals having up to 20,000 digits of precision, as determined by the @code{$ZPRECISION} intrinsic special variable, and @code{IEEE754}, to use IEEE 754 floating-point decimals. When in @code{IEEE754} mode, floating-point numbers support up to 16 digits of numeric precision.

@code{IEEE754} mode will make mathematical calculations significantly faster, especially when accelerated by a floating-point processor, at the expense of precision and accuracy.

@code{FIXED} mode is recommended for financial calculations, or where precision and accuracy are valued over performance. @code{FIXED} is the default mode of FreeM operation.

Attempting to @code{SET} this node to values other than @code{FIXED} or @code{IEEE754} will set @code{$ECODE} to @code{M29}.

@end table

@node ^$LOCK
@section ^$LOCK
@cindex ^$LOCK
@cindex structured system variables, ^$LOCK

The first-level subscript of @code{^$LOCK} is a lock name. The value at each node is the PID which owns the lock, a comma, and the lock counter for the locked resource.

Attempting to @code{SET} or @code{KILL} any node in @code{^$LOCK} will raise error @code{M29}.

@node ^$OBJECT
@section ^$OBJECT
@cindex ^$OBJECT
@cindex structured system variables, ^$OBJECT

@node ^$ROUTINE
@section ^$ROUTINE
@cindex ^$ROUTINE
@cindex structured system variables, ^$ROUTINE

The @code{^$ROUTINE} SSVN exposes a list of routines available in the current FreeM namespace, as well as additional attributes further describing each routine.

The first-level subscript is the name of a FreeM routine minus the leading caret symbol.

The following second-level subscripts are supported:

@table @asis

@item @code{CHARACTER} +R -U -D
Returns the character set of the routine.

@item @code{NAMESPACE} +R -U -D
Returns the name of the FreeM namespace in which the routine resides.

@item @code{PATH} +R -U -D
Returns the full filesystem path to the routine in fixed storage.

@end table

@node ^$SYSTEM
@section ^$SYSTEM
@cindex ^$SYSTEM
@cindex structured system variables, ^$SYSTEM

The @code{^$SYSTEM} SSVN exposes system-level implementation details.

The following first-level subscripts are supported:

@table @asis

@item @code{DEFPSIZE} +R -U -D
Returns the default size in bytes of the symbol table and routine buffer memory partition.

@item @code{DEFUDFSVSIZ} +R -U -D
Returns the default size in bytes of the user-defined intrinsic special variable table.

@item @code{DEFNSIZE} +R -U -D
Returns the default size of the @code{NEW} stack, in number of entries.

@item @code{MAXNO_OF_RBUF} +R -U -D
Returns the maximum number of routine buffers.

@item @code{DEFNO_OF_RBUF} +R -U -D
Returns the default number of routine buffers.

@item @code{DEFPSIZE0} +R -U -D
Returns the default size in bytes of each routine buffer.

@item @code{NO_GLOBLS} +R -U -D
Returns the maximum number of globals that can be concurrently opened.

@item @code{NO_OF_GBUF} +R -U -D
Returns the number of global buffers.

@item @code{NESTLEVLS} +R -U -D
Returns the depth of the @code{DO}, @code{FOR}, @code{XECUTE} stack.

@item @code{PARDEPTH} +R -U -D
Returns the maximum depth of the parser's parameter stack.

@item @code{PATDEPTH} +R -U -D
Returns the maximum number of @emph{patatom}s in each pattern.

@item @code{TRLIM} +R -U -D
Returns the trace limit of the @code{BUILTIN} global handler.

@item @code{ARGS_IN_ESC} +R -U -D
Returns the maximum number of arguments in a terminal escape sequence.

@item @code{ZTLEN} +R -U -D
Returns the maximum length of @code{$ZTRAP}.

@item @code{FUNLEN} +R -U -D
Returns the maximum length of the @code{$ZF} (function key) variable.

@item @code{NAME_LENGTH} +R -U -D
Returns the maximum length of variable names in the current FreeM build. Compatible with the same SSVN node in @emph{Reference Standard M}

@item @code{STRING_MAX} +R -U -D
Returns the maximum length of character strings in the current FreeM build. Compatible with the same SSVN node in @emph{Reference Standard M}

@item @code{$NEXTOK} +R -U -D
Returns a value indicating whether or not the @code{$NEXT} intrinsic function is allowed. In FreeM, @code{$NEXT} is always enabled, and this SSVN is provided solely for compatibility with @emph{Reference Standard M}. Thus, this SSVN node always returns @code{1}.

@item @code{EOK} +R -U -D
Returns a value indicating whether or not @code{E} notation for exponents is allowed. In FreeM, this feature is always enabled, and this SSVN is provided solely for compatibility with @emph{Reference Standard M}. Thus, this SSVN node always returns @code{1}.

@item @code{OFFOK} +R -U -D
Returns a value indicating whether or not offsets are allowed in @code{DO} and @code{GOTO}. In FreeM, this feature is always enabled, and this SSVN is provided solely for compatibility with @emph{Reference Standard M}. Thus, this SSVN node always returns @code{1}.

@item @code{BIG_ENDIAN} +R -U -D
Returns a 1 if FreeM is running on a big-endian platform, or a 0 otherwise. Compatible with the same SSVN node in @emph{Reference Standard M}.

@item @code{NAMESPACE} +R -U -D
The descendant subscripts of this node list each namespace in the current FreeM environment.

@item @code{MAPPINGS,GLOBAL} +R -U -D
Descendant subscripts of this node represent global name mappings set in @code{^$GLOBAL(@emph{gvn},"NAMESPACE")}

@end table

@node ^$WINDOW
@section ^$WINDOW
@cindex ^$WINDOW
@cindex structured system variables, ^$WINDOW

The @code{^$WINDOW} SSVN has no nodes yet defined. However, completing a @code{MERGE} to this SSVN will cause MWAPI-ish things to happen, and further work is proceeding on MWAPI implementation.

@node ^$ZPROCESS
@section ^$ZPROCESS
@cindex ^$ZPROCESS
@cindex structured system variables, ^$ZPROCESS

Provides access to @code{procfs}, which is a filesystem-like abstraction for UNIX process metadata contained in @code{/proc}, as well as features for examining and controlling the state of processes external to the FreeM interpreter.

The first subscript always represents the @emph{process ID} of the external process being acted upon.

The following values for the second subscript are supported:


@table @asis

@item @code{EXISTS} +R -U -D
Returns 1 if the referenced process exists; 0 otherwise.

@item @code{ATTRIBUTE} +R -U -D
Exposes the @code{/proc} files as descendant subscripts, i.e., @code{WRITE ^$ZPROCESS(2900,"ATTRIBUTE","cmdline"),!} would print the initial command line used to invoke process ID 2900. Note that the third subscript (the immediate descendant of the @code{ATTRIBUTE} subscript) is case sensitive.

@item @code{SIGNAL} -R +U -D
Allows signals to be sent to the referenced process. The following subscript is an integer value corresponding to the desired signal number. You may obtain a list of signal numbers on most UNIX systems with the command @code{kill -l}.

The constants @code{%SYS.SIGNAL.HUP}, @code{%SYS.SIGNAL.INT}, @code{%SYS.SIGNAL.KILL}, and @code{%SYS.SIGNAL.TERM} are provided for convenient use of this SSVN subscript.

@end table

@node ^$ZRPI
@section ^$ZRPI
@cindex ^$ZRPI
@cindex structured system variables, ^$ZRPI

The @code{^$ZRPI} structured system variable provides easy access to general-purpose input/output (GPIO) pins on Raspberry Pi single-board computers.

To initialize the GPIO subsystem, @code{SET ^$ZRPI("INITIALIZE")=1}.

Individual pins are accessed through @code{^$ZRPI("GPIO",<pin>,...)}, where @code{<pin>} represents the desired pin number. Descendant subscripts of @code{^$ZRPI("GPIO",<pin>)} are as follows:

@table @asis

@item @code{MODE} +R +U -D
Represents the operating mode of the selected pin. One of @code{INPUT}, @code{OUTPUT}, @code{PWM_OUTPUT}, or @code{GPIO_CLOCK}.

@item @code{DIGITAL} +R +U -D
Reads or writes the selected pin digitally. The value is limited to @code{1} or @code{0}.

@item @code{ANALOG} +R +U -D
Reads or writes the selected pin in an analog fashion. The value represents analog voltage.

@end table

@node Operators
@chapter Operators

@menu
* Unary +::                     Force a value to positive.
* Unary -::                     Force a value to negative.
* +::                           Add.
* +=::                          Add and assign.
* ++::                          Postfix increment.
* -::                           Subtract.
* -=::                          Subtract and assign.
* --::                          Postfix decrement.
* *::                           Multiply.
* *=::                          Multiply and assign.
* /::                           Divide.
* /=::                          Divide and assign.
* \::                           Integer divide.
* \=::                          Integer divide and assign.
* #::                           Modulo.
* #=::                          Modulo and assign.
* **::                          Exponentiate.
* **=::                         Exponentiate and assign.
* <::                           Less than.
* <=::                          Less than or equal to.
* >::                           Greater than.
* >=::                          Greater than or equal to.
* _::                           Concatenate.
* _=::                          Concatenate and assign.
* =::                           Equals.
* [::                           Contains.
* ]::                           Follows.
* ]]::                          Sorts after.
* ?::                           Pattern match.
* &::                           Logical AND.
* ! (Operator)::                Logical OR.
* '::                           Logical NOT.
* @@ (Operator)::               Indirect
@end menu

@node Unary +
@section Unary +
@cindex operators, unary +

Forces a number to positive, whether positive or negative. Also forces numeric coercion of strings.

@node Unary -
@section Unary -
@cindex operators, unary -

@node +
@section + (Add)
@cindex operators, +

@node +=
@section += (Add/Assign)
@cindex operators, +=

@node ++
@section ++ (Postfix Increment)
@cindex operators, ++

@node -
@section - (Subtract)
@cindex operators, -

@node -=
@section -= (Subtract/Assign)
@cindex operators, -=

@node --
@section -- (Postfix Decrement)
@cindex operators, --

@node *
@section * (Multiply)
@cindex operators, *

@node *=
@section *= (Multiply/Assign)
@cindex operators, *=

@node /
@section / (Divide)
@cindex operators, /

@node /=
@section /= (Divide/Assign)
@cindex operators, /=

@node \
@section \ (Integer Divide)
@cindex operators, \

@node \=
@section \= (Integer Divide/Assign)
@cindex operators, \=

@node #
@section # (Modulo)
@cindex operators, #

@node #=
@section #= (Modulo/Assign)
@cindex operators, #=

@node **
@section ** (Exponentiate)
@cindex operators, **

@node **=
@section **= (Exponentiate/Assign)
@cindex operators, **=

@node <
@section < (Less Than)
@cindex operators, <

@node <=
@section <= (Less Than or Equal To)
@cindex operators, <=

@node >
@section > (Greater Than)
@cindex operators, >

@node >=
@section >= (Greater Than or Equal To)
@cindex operators, >=

@node _
@section _ (Concatenate)
@cindex operators, _

@node _=
@section _= (Concatenate/Assign)
@cindex operators, _=

@node =
@section = (Equals)
@cindex operators, =

@node [
@section [ (Contains)
@cindex operators, [

@node ]
@section ] (Follows)
@cindex operators, ]

@node ]]
@section ]] (Sorts After)
@cindex operators, ]]

@node ?
@section ? (Pattern Match)
@cindex operators, ?

@node &
@section & (Logical AND)
@cindex operators, &

@node ! (Operator)
@section ! (Logical OR)
@cindex operators, !

@node '
@section ' (Logical NOT)
@cindex operators, '

@node @@ (Operator)
@section @@ (Indirect)
@cindex operators, @@

@node Routines
@chapter Routines
@cindex routines

A @emph{routine} is a file containing M source code to be processed by FreeM.

Routines exist within a @emph{namespace} (such as @code{SYSTEM} or @code{USER}), which in turn exist within an @emph{environment} (such as @code{DEFAULT}).

@menu
* Routine Naming::              Requirements and conventions for routine names.
@end menu


@node Routine Naming
@section Routine Naming
The routine's filename follows the format @code{NAME.m}, where @code{NAME} is the name of the routine, and @code{.m} is the filename extension.

Routine naming rules are as follows:

@itemize @bullet
@item Routine names must begin with an upper- or lower-case letter, or a @code{%} sign
@item Within the routine name, you may have upper-case or lower-case letters or digits
@item The entire routine name must not be longer than 255 characters
@end itemize

Routines whose names begin with @code{%} must be located in the @code{SYSTEM} namespace. Other routines may be located in any namespace.

@node Types
@chapter Types
@cindex types
@cindex data types

FreeM supports all @emph{libdatatype} types defined in the former MDC's @emph{Millennium Draft Standard}, with the exception of @code{MATRIX}, and with extensions supporting object-oriented programming. A notable enhancement in FreeM is that the library data types can be used in the @emph{formallist} of any extrinsic function or subroutine; not only in @emph{libraryelement}s.

@menu
* BOOLEAN::                     Truth values.
* COMPLEX::                     Numbers with real and imaginary parts.
* INTEGER::                     Numbers with no decimal part.
* REAL::                        Numbers with a decimal part.
* STRING::                      Arbitrary strings of characters.
* Custom Types (Classes)::      User-defined, object-oriented types.
@end menu

@node BOOLEAN
@section BOOLEAN
@cindex data types, BOOLEAN
@cindex types, BOOLEAN

The @code{BOOLEAN} type represents any M value that can be interpreted as a truth-value.

@node COMPLEX
@section COMPLEX
@cindex data types, COMPLEX
@cindex types, COMPLEX

The @code{COMPLEX} type is a complex number represented as a string in the format @code{@emph{<real-part>}%@emph{<imaginary-part>}}, where @emph{real-part} and @emph{imaginary-part} are both @code{REAL} numbers. See @ref{REAL} for more information.

FreeM will attempt to interpret any @code{COMPLEX} value according to the usual rules for M canonical numbers, i.e., the string @code{sabc123.345%fbd3.1} would be interpreted as a complex number with the real part being @code{123.345} and the imaginary part being @code{3.1}.

@node INTEGER
@section INTEGER
@cindex data types, INTEGER
@cindex types, INTEGER

An @code{INTEGER} is an interpretation of numeric data with any fractional part removed.

@node REAL
@section REAL
@cindex data types, REAL
@cindex types, REAL

@node STRING
@section STRING
@cindex data types, STRING
@cindex types, STRING

@node Custom Types (Classes)
@section Custom Types (Classes)
@cindex data types, custom
@cindex types, custom
@cindex classes

See @ref{Classes}.

@node Globals
@chapter Globals
@cindex globals
@cindex variables, global
@cindex data

@node Concurrency Control
@chapter Concurrency Control
@cindex concurrency control
@cindex locking
@cindex transaction processing

@node Local Variables
@chapter Local Variables
@cindex variables, local
@cindex local variables

@node Scoping
@chapter Scoping
@cindex scoping

@node Decision Constructs
@chapter Decision Constructs
@cindex decision constructs
@cindex IF
@cindex ELSE
@cindex THEN
@cindex postconditionals

@node Branch Constructs
@chapter Branch Constructs
@cindex branch constructs
@cindex DO
@cindex GOTO
@cindex JOB

@node Loop Constructs
@chapter Loop Constructs
@cindex loop constructs
@cindex FOR

@node Modular Programming
@chapter Modular Programming
@cindex modular programming
@cindex functions, extrinsic
@cindex subroutines

@menu
* Subroutines::         Making sections of code reusable.
* Extrinsic Functions:: Reusable code that returns a value.
@end menu

@node Subroutines
@section Subroutines

@node Extrinsic Functions
@section Extrinsic Functions

@node Object-Oriented Programming
@chapter Object-Oriented Programming
@cindex object-oriented programming
@cindex programming, object-oriented

@menu
* Classes::             The basis of object-oriented programming.
@end menu

@node Classes
@section Classes

@menu
* Inheritance::         Basing one class upon another.
* Methods::             Attaching code to a class.
* Public Variables::    Variables visible outside of a class.
* Private Variables::   Variables only visible within a class.
@end menu

@node Inheritance
@subsection Inheritance

@node Methods
@subsection Methods

@node Public Variables 
@subsection Public Variables

@node Private Variables
@subsection Private Variables

@node Libraries
@chapter Libraries
@cindex libraries

@node Sequential I/O
@chapter Sequential I/O

@node Network I/O
@chapter Network I/O
@cindex networks, input and output

Network I/O in FreeM is supplied through I/O channels 100-255. The normal @code{READ} and @code{WRITE} syntax will work with network sockets, with a few exceptions.

@section Opening and Connecting a Client Socket
@cindex networks, opening and connecting client sockets

To open a client socket and connect to it, you will need to call the @code{OPEN} command and the @code{USE} command:

@example
  ;
  ; Set socket read terminator to LF
  ;
  SET ^$DEVICE(100,"OPTIONS","TERMINATOR")=$C(10)
  ;
  ; Open an IPv4 TCP socket to mail.mydomain.com on port 25 (SMTP)
  ; and connect to it
  ;
  OPEN 100:"mail.mydomain.com:25:IPV4:TCP"
  USE 100:/CONNECT
  ;
  ; Read a line of input from the remote host and write it to the terminal
  ;
  NEW LINE
  READ LINE
  USE 0
  WRITE LINE,!
  ;
  ; CLOSE the socket and disconnect
  ;
  CLOSE 100
  QUIT
@end example

@node Extended Global References
@chapter Extended Global References
@cindex global references, extended
@cindex extended global references

@section Standard Extended Global References
@cindex extended global references, standard

FreeM supports extended global references, allowing the user to access globals in namespaces other than the current default namespace and the @code{SYSTEM} namespace, without switching to the other namespace.

For example, if you are in the @code{USER} namespace, the following code will print the value of @code{^VA(200,0)} in the @code{VISTA} namespace:

@example
  WRITE ^|"VISTA"|VA(200,0),!
@end example

You may also use an expression that resolves to a string containing a valid namespace name:

@example
  SET NS="VISTA"
  WRITE ^|NS|VA(200,0),!
@end example  

@section File Path Extended Global References
@cindex extended global references, file path

If a namespace is configured to use the @code{BUILTIN} global handler, FreeM supports accessing a global data file by way of its filesystem path.

The following file path extended global reference will write the value of @code{^VA(200,0)}, assuming the @code{^VA} data file exists at path @code{/home/jpw/^VA}:

@example
  WRITE ^/home/jpw/VA(200,0),!
@end example


@node Global Aliasing
@chapter Global Aliasing
@cindex aliasing, global
@cindex globals, aliasing

FreeM provides the ability to set alternative names for M global variables.

To create an alias of @code{^FOO} named @code{^BAR}, use the following command:

@example
  SET ^$JOB($JOB,"ALIASES","^BAR")="^FOO"
@end example

If such an alias is set, any reference to global variable @code{^BAR} will affect @code{^FOO} instead of @code{^BAR} until @code{^$JOB($JOB,"ALIASES","^BAR")} is @code{KILL}ed. If @code{^BAR} existed prior to the definition of this alias, its data will be unavailable to and unaffected by application code.  

@node Global Mappings
@chapter Global Mappings
@cindex mappings, global
@cindex globals, mapping

FreeM supports creating persistent mappings through which arbitrary global names may be mapped to specific namespaces. This allows non-@code{%} globals to be stored in the @code{SYSTEM} namespace, or @code{%} globals to be stored in non-@code{SYSTEM} namespaces.

To map the @code{^FOO} global to the @code{SYSTEM} namespace, any of the following will work:

@example
  MAP GLOBAL ^FOO="SYSTEM"
  SET ^$GLOBAL("FOO","NAMESPACE")="SYSTEM"
  SET ^$SYSTEM("MAPPINGS","GLOBAL","^FOO")="SYSTEM"
@end example

There is no functional difference in any of the three approaches; the method you choose is a matter of personal preference.

To remove the above mapping, any of the following examples will also work:

@example
  UNMAP GLOBAL ^FOO
  KILL ^$GLOBAL("FOO","NAMESPACE")
  KILL ^$SYSTEM("MAPPINGS","GLOBAL","^FOO")
@end example

@node Transaction Processing
@chapter Transaction Processing
@cindex transaction processing

FreeM implements a significant subset of the transaction processing features from @emph{ANSI X11.1-1995}. This allows a series of global operations to be conducted all at once, either in batch mode (where concurrency is not disturbed), or in serial mode (where writes are guaranteed to be atomic, consistent, isolated, and durable).

@section Theory of Operation

FreeM uses a pessimistic concurrency control mechanism for @code{SERIAL} transactions, meaning that any @code{TSTART} command that includes the @code{SERIAL} transaction parameter will cause the process to acquire the transaction processing mutex, which prevents any process but the one holding the mutex from performing any data access (read or write) until either @code{TCOMMIT} or @code{TROLLBACK} is called, either committing or rolling back the transaction, respectively.

Any transaction in between its @code{TSTART} and @code{TCOMMIT}/@code{TROLLBACK} is said to be @emph{in-flight}. During the in-flight stage, pending global operations are held only in memory and after-image journals.

FreeM maintains a list of all globals affected during a transaction in-flight. When a @code{TCOMMIT} is reached, FreeM will generate a @emph{checkpoint} of each global data file to be changed by the transaction. These checkpoints allow all FreeM globals to be restored to their pre-transaction state if a @code{TCOMMIT} should fail part of the way through its operation. 

Checkpoints can have one of two modes:

@table @asis

@item @code{CP_REMOVE}
Used for globals that did not exist prior to the beginning of this transaction. Simply marks the entire global data file for deletion in case of @code{TCOMMIT} failure.

@item @code{CP_RESTORE}
Used for globals that @emph{did} exist prior to the beginning of this transaction. In this case, the entire global data file is copied to a new file with a @code{.chk} extension. In cases of @code{TCOMMIT} failure, @code{CP_RESTORE} checkpoint files will be restored over the partially-modified live data file.

@end table

The below example shows a few global operations and checkpoints for a transaction in-flight using the @code{trantab} direct-mode command:

@verbatim
TL1:USER> trantab
 $TLEVEL 1*
  Operations for Transaction ID: 6ea14aad-b8f1-47f9-9f52-4f513f892bc0 [RESTARTABLE SERIAL]

   OP. NO.   ACTION         KEY/DATA
   -------   ------         --------
   1         SET            ^FOO=3
   2         KILL           ^FOO
   3         SET            ^jpw=10
   4         SET            ^BRANDNEW=6

  Global checkpoints:

   GLOBAL                        MODE                FILES
   ------                        ----                -----
   ^BRANDNEW                     CP_REMOVE           IN:   /usr/local/var/freem/USER/globals/^BRANDNEW
   ^jpw                          CP_RESTORE          IN:   /usr/local/var/freem/USER/globals/^jpw
                                                     OUT:  /usr/local/var/freem/USER/globals/^jpw.23390.1.chk
   ^FOO                          CP_RESTORE          IN:   /usr/local/var/freem/USER/globals/^FOO
                                                     OUT:  /usr/local/var/freem/USER/globals/^FOO.23390.1.chk
@end verbatim

In the above example, @code{IN} files are the live data file that will be overwritten or removed, and @code{OUT} files are the checkpoints themselves. Note that @code{OUT} files are only used for @code{CP_RESTORE} checkpoints.


@node Asynchronous Event Handling
@chapter Asynchronous Event Handling
@cindex event handling, asynchronous

Asynchronous event handling in FreeM follows the specifications of the unpublished MDC @emph{Millennium Draft Standard}.

@section Setting Up Async Event Handlers

Asynchronous event handlers are configured through the @code{^$JOB} structured system variable for job-specific events, and the @code{^$SYSTEM} structured system variable for system-wide events. In order to become proficient in writing asynchronous event handling code, you need to be aware of several important concepts:

@table @emph

@item Event Classes
@emph{Event classes} denote particular categories of events. These include @code{COMM}, @code{HALT}, @code{IPC}, @code{INTERRUPT}, @code{POWER}, @code{TIMER}, @code{TRIGGER}, and @code{USER} event classes. At present, only @code{INTERRUPT} and @code{TRIGGER} event classes are supported.

@item Event Identifiers
@emph{Event identifiers} denote the precise nature of the event that has occurred. For instance, resizing the terminal window in which a FreeM job is running will send an event of class @code{INTERRUPT} with an event identifier of @code{SIGWINCH} (short for @emph{SIGnal WINdow CHange}).

@item Event Handlers
@emph{Event handlers} are M routines or subroutines that can be registered to run when an event of a certain event class occurs.

@item Event Registration
@emph{Event registration} is the process of modifying the @code{^$JOB} or @code{^$SYSTEM} SSVN to associate a particular event class and event identifier with an event handler routine or subroutine.

@item Event Blocking and Unblocking
@emph{Event blocking} is the means by which asynchronous event handling can be temporarily suspended. For example, asynchronous events are temporarily and implicitly blocked for the duration of event handler execution, unless explicitly un-blocked within the event handler. Event handling can also be blocked and unblocked programatically from M code using the @code{ABLOCK} and @code{AUNBLOCK} commands.

@end table

The following sections of this chapter will take you step-by-step through setting up an event handler for @code{SIGWINCH} signal handling.

@section Registering an Asynchronous Event Handler
@cindex event handlers, registration

To register a job-specific event handler that will only execute in the current FreeM process, use the following syntax:

@example
  SET ^$JOB($JOB,"EVENT",@emph{event-class},@emph{event-identifier})=@emph{entryref}
@end example

To register a system-wide event handler that will execute in every FreeM process, use the following syntax:

@example
  SET ^$SYSTEM("EVENT",@emph{event-class},@emph{event-identifier})=@emph{entryref}
@end example

For example, use the following to register @code{^RESIZE} as an asynchronous event handler for @code{SIGWINCH} events:

@example
  SET ^$JOB($JOB,"EVENT","INTERRUPT","SIGWINCH")="^RESIZE"
@end example

This by itself will not enable asynchronous event handling, as it merely @emph{registers} an event handler, associating it with event class @code{INTERRUPT} and event identifier @code{SIGWINCH}.

@section Enabling Asynchronous Event Handling
@cindex event handlers, enabling

In order to enable asyncronous event handling, the @code{ASTART} command is used. In the following example, we will enable asynchronous event handling for the @code{INTERRUPT} event class:

@example
  ASTART "INTERRUPT"
@end example

Omitting the @code{"INTERRUPT"} argument will enable asynchronous event handling for @emph{all} event classes. See @code{ASTART} in the commands section for more details.

Once this is done, any event handlers registered for the @code{INTERRUPT} event class in @code{^$JOB} will be executed asynchronously as appropriate.

Please note that @code{ASTART "TRIGGER"} is run implicitly at FreeM startup, to ensure consistency in applications depending on business logic contained in system-wide global triggers. To disable this behavior, add @code{ASTOP "TRIGGER"} to the @code{LOCAL.STARTUP} routine in the @code{USER} namespace. If @code{LOCAL.STARTUP} does not yet exist in your environment, you may create it by typing @code{fmadm edit routine USER LOCAL.STARTUP} from your UNIX command-line shell.

@section Disabling Asynchronous Event Handling
@cindex event handlers, disabling

To disable asynchronous event handling, the @code{ASTOP} command is used. In the following example, we will disable asynchronous event handling for the @code{INTERRUPT} event class:

@example
  ASTOP "INTERRUPT"
@end example

Omitting the @code{"INTERRUPT"} argument will disable asynchronous event handling for @emph{all} event classes. See @code{ASTOP} in the commands section for more details.

You may also disable asynchronous event handling for a specific event identifier by @code{KILL}ing the appropriate node in the @code{^$JOB} SSVN, which unregisters the event handler altogether. The following example will unregister the event handler for the @code{SIGWINCH} event identifier:

@example
  KILL ^$JOB($JOB,"EVENT","INTERRUPT","SIGWINCH")
@end example  

@section Temporarily Blocking Asynchronous Event Handling
@cindex event handlers, blocking

To temporarily block processing of specific event classes, you will use the @code{ABLOCK} command. @code{ABLOCK} functions incrementally, that is, each successive call to @code{ABLOCK} will increment a counter of blocks held for the specified event class or classes, and each successive call to @code{AUNBLOCK} will decrement that counter. Event handling for the specified event classes will be blocked as long as the @code{ABLOCK} counter for those classes is greater than zero. Thus, event blocking is cumulative, in a manner similar to M incremental locks.

The following example blocks asynchronous event handling for the @code{INTERRUPT} event class:

@example
  ABLOCK "INTERRUPT"
@end example

Note that entering an event handler causes an implicit @code{ABLOCK} of @emph{all} event classes, to prevent event handlers from interrupting other event handlers during their execution. This may be overridden by calling @code{AUNBLOCK} for one or more event classes within an event handler. However, unblocking event handling during an event handler should be done with great caution, as this can make the flow of code execution somewhat unpredictable, especially if M globals are modified inside of an event handler routine or subroutine.

Modifying M globals within event handlers is allowed but strongly discouraged, as doing so can lead to logical corruption of the data. If you must modify an M global within an event handler, guard all such operations with prodigious and careful use of @code{LOCK}s, ensuring that such modifications occur in the desired logical order.

@node Global Triggers
@chapter Global Triggers
@cindex global triggers
@cindex triggers

Global triggers use the FreeM asynchronous event handling subsystem to allow a FreeM process to execute arbitrary M code when a particular action occurs on a particular global.

To set up a global trigger, you must set up an event handler for event class @code{TRIGGER}. The event identifier must be in the format of @code{"<action>:<gvn>"}, where @emph{<gvn>} is a global variable name, and @emph{<action>} is one of the following:

@table @asis

@item @code{DATA}
Trigger will fire when the @code{$DATA} intrinsic function is called on @emph{<gvn>}.

@item @code{GET}
Trigger will fire when @emph{<gvn>} is read from.

@item @code{INCREMENT}
Trigger will fire when intrinsic function @code{$INCREMENT} is called on @emph{<gvn>}.

@item @code{KILL}
Trigger will fire when @emph{<gvn>} is @code{KILL}ed.

@item @code{NEXT}
Trigger will fire when intrinsic function @code{$NEXT} is called on @emph{<gvn>}.

@item @code{ORDER}
Trigger will fire when intrinsic function @code{$ORDER} is called on @emph{<gvn>}.

@item @code{QUERY}
Trigger will fire when intrinsic function @code{$QUERY} is called on @emph{<gvn>}.

@item @code{SET}
Trigger will fire when @code{SET @emph{<gvn>}=@emph{value}} occurs.

@item @code{ZDATA}
Trigger will fire when intrinsic function @code{ZDATA} is called on @emph{<gvn>}.

@end table

When a @code{TRIGGER} event occurs, the @code{"GLOBAL"} node of the @code{^$EVENT} structured system variable will be populated with the global reference that invoked the trigger event.

If a @code{SET} or @code{KILL} trigger was the source of the @code{TRIGGER} event, the @code{OLD_VALUE} node of @code{^$EVENT} will be populated with original value of @code{^$EVENT("GLOBAL")} prior to the change, and @code{NEW_VALUE} will be populated with the new value. This allows triggers to contain logic to undo global changes. This functionality can also be used to provide auditing of specific global changes.

The following example shows a trigger implemented for @code{SET} operations on the @code{^DD} global.

@example
TRIGGER ;
    ;
    ; Set up a SET trigger on ^DD
    ;
    SET ^$JOB($JOB,"EVENT","TRIGGER","SET:^DD")="ONSET^TRIGGER"
    ;
    ; Enable the TRIGGER event class
    ;
    ASTART "TRIGGER"
    ;
    ; Try setting a node in ^DD
    ;
    SET ^DD(1)="Test"
    ;
    ; Quit
    ;
    QUIT
    ;
    ;
ONSET ;
    WRITE "The "_^$EVENT("GLOBAL")_" global node was SET.",!
    QUIT
@end example

You can also set up a trigger that applies to all FreeM processes by setting descendant subscripts of @code{^$SYSTEM("EVENT","TRIGGER",...)} instead of using @code{^$JOB($JOB,"EVENT","TRIGGER",...)}.

@node Synchronous Event Handling
@chapter Synchronous Event Handling

@node GUI Programming with MWAPI
@chapter GUI Programming with MWAPI

@node User-Defined Z Commands
@chapter User-Defined Z Commands

@node User-Defined Z Functions
@chapter User-Defined Z Functions

@cindex z functions, user-defined

@node User-Defined SSVNs
@chapter User-Defined SSVNs 

@cindex structured system variables, user-defined
@cindex structured system variables

@node Language Dialects
@chapter Language Dialects

@cindex language dialects
@cindex dialects, language


@node System Library Routines
@chapter System Library Routines
@cindex system library routines

@section ^%ZCOLUMNS
@cindex ^%ZCOLUMNS
@cindex system library routines, ^%ZCOLUMNS

This routine is the implementation of the @code{$ZCOLUMNS} intrinsic special variable.

@section ^%SYSINIT
@cindex ^%SYSINIT
@cindex system library routines, ^%SYSINIT

This routine is the default startup routine for FreeM running in direct mode.

Running @code{DO INFO} from direct mode will use this routine to display information about the current FreeM status and namespace configuration.

@section ^%ZHELP
@cindex ^%ZHELP
@cindex system library routines, ^%ZHELP

This routine implements the online help feature of FreeM, invoked by typing @code{?} in direct mode. It simply asks the underlying system to execute the command @command{info freem}.

@section ^%ZROWS
@cindex ^%ZROWS
@cindex system library routines, ^%ZROWS

This routine is the implementation of the @code{$ZROWS} intrinsic special variable.

@node Interrupt Handling
@chapter Interrupt Handling
@cindex interrupt handling

When FreeM receives the @code{SIGINT} signal, either by pressing @code{Ctrl-C} during program execution, or by external signal from the operating system, the FreeM daemon, or another external process, one of two things can happen, depending on the state of the @code{$ZI} special variable:

@table @asis
@item @code{$ZI} evaluates @emph{true}
In this case, the @code{ZINRPT} error is raised, and normal error handling procedures apply. If neither @code{$ZTRAP} nor @code{$ETRAP} are set, FreeM prints an error diagnostic on the home device and will exit the FreeM process in application mode (i.e., the @code{freem} executable was started with the @code{--routine} or @code{-r} flag), or return to the direct mode prompt otherwise.

This is the default behavior of FreeM.
@item @code{$ZI} evaluates @emph{false}
In this case, no error is raised, but the @code{$ZCONTROLC} flag is set. In this mode of operation, it is up to program code to check for @code{$ZCONTROLC} and take appropriate action.

Checking the value of @code{$ZCONTROLC} will reset it to @emph{false}.
@end table

In either case, if asynchronous event handling is enabled for the @code{INTERRUPT} event class (i.e., @code{ASTART "INTERRUPT"} or @code{ASTART} have been invoked by the current process), an asynchronous event of event class @code{INTERRUPT} and event identifier @code{SIGINT} will be enqueued. 

@node Error Processing
@chapter Error Processing
@cindex error processing

FreeM exposes three means of processing M program execution errors:

@table @emph

@item FreeM-style error processing
FreeM-style error processing exposes a read/write error trap in @code{$ZTRAP}. The contents of @code{$ZTRAP} must be either empty or a valid M entryref, to which FreeM will @code{GOTO} if an error occurs. Each program stack execution level can have its own @code{$ZTRAP} error handler enabled.

@item DSM 2.0-style error processing
DSM 2.0-style error processing emulates the @code{$ZTRAP} behavior of Digital Standard MUMPS v2. It has the same behavior as FreeM-style error handling, with the exception that in DSM 2.0-style error processing, only one @code{$ZTRAP} error handler is set across all program stack execution levels.

@item Standard error processing
Standard error processing uses the @code{NEW}-able @code{$ETRAP} variable to store error handler code, which may be any valid M code. The code in @code{$ETRAP} will run when an error occurs or the @code{$ECODE} ISV becomes non-empty. Stack information for standard error handling is provided by the @code{$STACK} ISV, the @code{$STACK()} intrinsic pseudo-function, and the @code{NEW}-able @code{$ESTACK} ISV.

If @code{$ETRAP} is non-empty when an error condition occurs, @code{$ZTRAP} is ignored, regardless of whether FreeM-style or DSM 2.0-style error processing is enabled at the time of the error.

@end table

For further information on switching between FreeM-style and DSM 2.0-style @code{$ZTRAP} error handling, see the documentation for the @code{BREAK} command.

@node FreeM Error Codes
@chapter FreeM Error Codes
@cindex Error Codes

@table @asis

@item @code{ZINRPT} - @emph{interrupt}
Raised when an interrupt signal is received.

@item @code{ZBKERR} - @emph{BREAK point}
Raised when a @code{BREAK} point is reached.

@item @code{ZNOSTAND} - @emph{non standard syntax}
Raised when features incompatible with the current value of @code{$DIALECT} are used.

@item @code{ZUNDEF} - @emph{variable not found}
Raised when an undefined local or global variable is accessed. This error code has been deprecated in favor of standard error codes @code{M6} and @code{M7}.

@item @code{ZLBLUNDEF} - @emph{label not found}
Raised when a referenced label is not found.

@item @code{ZMISSOPD} - @emph{missing operand}
Raised when an operand is missing from an expression.

@item @code{ZMISSOP} - @emph{missing operator}
Raised when an operator is missing from an expression.

@item @code{ZILLOP} - @emph{unrecognized operator}
Raised when an unrecognized operator is encountered in an expression.

@item @code{ZQUOTER} - @emph{unmatched quotes}
Raised when unbalanced quotes are encountered.

@item @code{ZCOMMAER} - @emph{comma expected}
Raised when a comma is expected in program syntax but is not found.

@item @code{ZASSIGNER} - @emph{equals '=' expected}
Raised when an equals sign is expected in program syntax but is not found.

@item @code{ZARGER} - @emph{argument not permitted}
Raised when an argument is encountered in a syntactic position where arguments are not permitted.

@item @code{ZSPACER} - @emph{blank ' ' expected}
Raised when a space character is expected in program syntax but is not found.

@item @code{ZBRAER} - @emph{unmatched parentheses}
Raised when unbalanced parentheses are detected in program syntax.

@item @code{ZLVLERR} - @emph{level error}
Raised when a level error occurs.

@item @code{ZDIVER} - @emph{divide by zero}
Raised when program code attempts to divide by zero. Deprecated in favor of standard error code @code{M9}.

@item @code{ZILLFUN} - @emph{function not found}
Raised when program code attempts to call intrinsic or extrinsic functions that are not defined.

@item @code{ZFUNARG} - @emph{wrong number of function arguments}
Raised when an intrinsic or extrinsic function is called with the wrong number of arguments.

@item @code{ZZTERR} - @emph{ZTRAP error}
Raised when a @code{$ZTRAP} error occurs.

@item @code{ZNEXTERR} - @emph{$NEXT/$ORDER error}
Raised when an error occurs in @code{$NEXT} or @code{$ORDER}.

@item @code{ZSELER} - @emph{$SELECT error}
Raised when an error occurs in @code{$SELECT}

@item @code{ZCMMND} - @emph{illegal command}
Raised when program code attempts to execute an illegal command.

@item @code{ZARGLIST} - @emph{argument list incorrect}
Raised when the argument list supplied to an M language element does not match that language element's syntactic requirements.

@item @code{ZINVEXPR} - @emph{invalid expression}
Raised when an invalid expression is encountered.

@item @code{ZINVREF} - @emph{invalid reference}
Raised when an invalid variable reference is encountered.

@item @code{ZMXSTR} - @emph{string too long}
Raised when a string is encountered that exceeds @code{^$SYSTEM("STRING_MAX")}.

@item @code{ZTOOPARA} - @emph{too many parameters}
Raised when too many parameters are passed to a function or subroutine.

@item @code{ZNOPEN} - @emph{unit not open}
Raised when attempting to access an I/O channel that has not been opened.

@item @code{ZNODEVICE} - @emph{unit does not exist}
Raised when attempting to access a device that does not exist.

@item @code{ZPROTECT} - @emph{file protection violation}
Raised when attempting to access a file or device to which you do not have permission.

@item @code{ZGLOBER} - @emph{global not permitted}
Raised when attempting to use a global in a syntactic element where global variables are not permitted.

@item @code{ZFILERR} - @emph{file not found}
Raised when attempting to access a file that does not exist.

@item @code{ZPGMOV} - @emph{program overflow}
Raised when a program overflows the limits of a routine buffer.

@item @code{ZSTKOV} - @emph{stack overflow}
Raised when @code{DO}, @code{FOR}, or @code{XECUTE} nesting levels exceed the value in @code{^$SYSTEM("NESTLEVLS")}.

@item @code{ZSTORE} - @emph{symbol table overflow}
Raised when program code attempts to store too much data in the local symbol table. Should not occur unless symbol table auto-adjust is disabled.

@item @code{ZNOREAD} - @emph{file won't read}
Raised when program code attempts to read from an unreadable file.

@item @code{ZNOWRITE} - @emph{file won't write}
Raised when program code attempts to write to an unwritable file.

@item @code{ZNOPGM} - @emph{routine not found}
Raised when an attempt is made to load or execute a routine that does not exist in the current namespace.

@item @code{ZNAKED} - @emph{illegal naked reference}
Raised when an attempt is made to use an illegal naked reference.

@item @code{ZSBSCR} - @emph{illegal subscript}
Raised when an illegal subscript access is attempted.

@item @code{ZISYNTX} - @emph{insert syntax}
Raised when illegal insert syntax is used.

@item @code{ZDBDGD} - @emph{global data degradation}
Raised when corruption is detected in global data files.

@item @code{ZKILLER} - @emph{job kill signal}
Raised on a job kill signal.

@item @code{ZHUPER} - @emph{hangup signal}
Raised on a job hangup signal.

@item @code{ZMXNUM} - @emph{numeric overflow}
Raised when an assignment or expression result exceeds @code{$ZPRECISION}.

@item @code{ZNOVAL} - @emph{function returns no value}
Raised when a function does not return a value. Extrinsic functions must @code{QUIT} with a value.

@item @code{ZTYPEMISMATCH} - @emph{type mismatch}
Raised when a type mismatch occurs.

@item @code{ZMEMOV} - @emph{out of memory}
Raised when FreeM runs out of heap memory.

@item @code{ZNAMERES} - @emph{error in name resolution}
Raised when an attempted name resolution fails.

@item @code{ZSCKCREAT} - @emph{error creating socket}
Raised when an error occurs creating a socket for network I/O.

@item @code{ZSCKIFAM} - @emph{invalid address family (must be IPV4 or IPV6)}
Raised when the address family specified in an @code{OPEN} command for a socket I/O channel is not IPV4 or IPV6.

@item @code{ZSCKITYP} - @emph{invalid connection type (must be TCP or UDP)}
Raised when the connection type specified in an @code{OPEN} command for a socket I/O channel is not @code{TCP} or @code{UDP}.

@item @code{ZSCKIPRT} - @emph{invalid port number}
Raised when the port number specified in an @code{OPEN} command for a socket I/O channel is invalid. Valid TCP and UDP ports are in the range of 1-65535.

@item @code{ZSCKCERR} - @emph{connection error}
Raised when an error occurs on a @code{USE <channel>:/CONNECT} command.

@item @code{ZSCKAERR} - @emph{USE action invalid for connection type (possibly CONNECT on UDP socket?)}
Raised when an attempt is made to @code{USE <channel>:/CONNECT} on a UDP socket I/O channel. The UDP protocol is connectionless.

@item @code{ZSCKACON} - @emph{attempted to CONNECT an already-connected socket}
Raised when an attempt is made to @code{USE <channel>:/CONNECT} on a TCP socket I/O channel that is already connected.

@item @code{ZSCKNCON} - @emph{attempted to READ from a disconnected TCP socket}
Raised when an attempt is made to @code{READ} a TCP socket that has not yet been connected.

@item @code{ZSCKEOPT} - @emph{error setting socket options}
Raised when an error is encountered while setting socket options.

@item @code{ZSCKERCV} - @emph{error in READ from socket}
Raised when an error occurs in a socket I/O channel @code{READ}.

@item @code{ZSCKESND} - @emph{error in WRITE to socket}
Raised when an error occurs while attempting to @code{WRITE} to a socket I/O channel.

@item @code{ZNORPI} - @emph{^$ZRPI only supported on Raspberry Pi hardware}
Raised when an attempt is made to use the @code{^$ZRPI} structured system variable on a platform other than the Raspberry Pi single-board computer.

@item @code{ZCREDEF} - @emph{cannot redefine CONST}
Raised when attempts are made to redefine a @code{CONST} after its initial definition.

@item @code{ZCMODIFY} - @emph{cannot modify CONST}
Raised when attempts are made to change the value of a @code{CONST}.

@item @code{ZFILEXWR} - @emph{cannot open existing file for WRITE}
Raised when an attempt is made to open an existing file in write (but not append) mode.

@item @code{INEWMULT} - @emph{initializing NEW with multiple setarguments not supported}
Raised when you attempt to use multiple setarguments with initializing @code{NEW}, e.g. @code{NEW X=2,Y=3}.

@item @code{ZECODEINV} - @emph{invalid value for $ECODE}
Raised when attempts are made to set @code{$ECODE} to an invalid error code value. Obsolete and replaced by standard error code @code{M101}.

@item @code{ZASSERT} - @emph{programmer assertion failed}
Raised when an @code{ASSERT} expression's result is not true.

@item @code{ZUSERERR} - @emph{user-defined error}
Raised when program code calls @code{THROW} with an error code argument for which the first character is @code{U}, or when @code{$ECODE} is set to an error code for which the first character is @code{U}.

Custom error messages for @code{ZUSERERR} may be set in @code{^$JOB($JOB,"USER_ERRORS",<user_error_code>)}, where @code{<user_error_code>} represents the custom error code.

For example:

@example
USER> S ^$JOB($JOB,"USER_ERRORS","UBLACKHOLE")="black hole encountered"


USER> THROW UBLACKHOLE


>> Error UBLACKHOLE:  black hole encountered in SYSTEM::^%SYSINIT  [$STACK = 0]
>> THROW UBLACKHOLE
                  ^
@end example

@item @code{ZSYNTERR} - @emph{syntax error}
Raised when a syntax error without a more specific error code is encountered.

@item @code{ZCTRLB} - @emph{break}
Pseudo-error used by the FreeM debugger. Not visibly raised in normal program operation.

@item @code{ZASYNC} - @emph{asynchronous interruption}
Pseudo-error used by the FreeM asynchronous events subsystem. Not visibly raised in normal program operation.

@item @code{M1} - @emph{naked indicator undefined}
Raised when an attempt is made to use a naked reference before the naked indicator is set.

@item @code{M2} - @emph{invalid combination with $FNUMBER code atom}


@item @code{M3} - @emph{$RANDOM seed less than 1}


@item @code{M4} - @emph{no true condition in $SELECT}


@item @code{M5} - @emph{line reference less than zero}


@item @code{M6} - @emph{undefined local variable}


@item @code{M7} - @emph{undefined global variable}


@item @code{M8} - @emph{undefined intrinsic special variable}


@item @code{M9} - @emph{divide by zero}


@item @code{M10} - @emph{invalid pattern match range}


@item @code{M11} - @emph{no parameters passed}


@item @code{M12} - @emph{invalid line reference (negative offset)}


@item @code{M13} - @emph{invalid line reference (line not found)}


@item @code{M14} - @emph{line level not 1}


@item @code{M15} - @emph{undefined index variable}


@item @code{M16} - @emph{argumented QUIT not allowed}


@item @code{M17} - @emph{argumented QUIT required}


@item @code{M18} - @emph{fixed length READ not greater than zero}


@item @code{M19} - @emph{cannot copy a tree or subtree onto itself}


@item @code{M20} - @emph{line must have a formal parameter list}


@item @code{M21} - @emph{algorithm specification invalid}


@item @code{M22} - @emph{SET or KILL to ^$GLOBAL when data in global}


@item @code{M23} - @emph{SET or KILL to ^$JOB for non-existent job number}


@item @code{M24} - @emph{change to collation algorithm while subscripted local variables defined}


@item @code{M26} - @emph{non-existent environment}


@item @code{M27} - @emph{attempt to rollback a transaction that is not restartable}


@item @code{M28} - @emph{mathematical function, parameter out of range}


@item @code{M29} - @emph{SET or KILL on structured system variable not allowed by implementation}


@item @code{M30} - @emph{reference to global variable with different collating sequence within a collating algorithm}


@item @code{M31} - @emph{control mnemonic used for device without a mnemonic space selected}


@item @code{M32} - @emph{control mnemonic used in user-defined mnemonic space which has no associated line}


@item @code{M33} - @emph{SET or KILL to ^$ROUTINE when routine exists}


@item @code{M35} - @emph{device does not support mnemonic space}


@item @code{M36} - @emph{incompatible mnemonic spaces}


@item @code{M37} - @emph{READ from device identified by empty string}


@item @code{M38} - @emph{invalid structured system variable subscript}


@item @code{M39} - @emph{invalid $NAME argument}


@item @code{M40} - @emph{call-by-reference in JOB actual parameter}


@item @code{M41} - @emph{invalid LOCK argument within a transaction}


@item @code{M42} - @emph{invalid QUIT within a transaction}


@item @code{M43} - @emph{invalid range value ($X, $Y}


@item @code{M44} - @emph{invalid command outside of a transaction}


@item @code{M45} - @emph{invalid GOTO reference}


@item @code{M56} - @emph{identifier exceeds maximum length}


@item @code{M57} - @emph{more than one defining occurrence of label in routine}


@item @code{M58} - @emph{too few formal parameters}


@item @code{M60} - @emph{illegal attempt to use an undefined SSVN}


@item @code{M101} - @emph{invalid value for $ECODE}


@item @code{M102} - @emph{synchronous and asynchronous event processing cannot be simultaneously enabled for the same event class}


@item @code{M103} - @emph{invalid event identifier}


@item @code{M104} - @emph{ETRIGGER event identifier for IPC event class does not match job process identifier}


@end table

@node Debugging
@chapter Debugging
@cindex debugging

@node System Configuration
@chapter System Configuration
@cindex configuration, system

@section Installing FreeM
@cindex installation

@section Build Configuration
@cindex build configuration

When configuring FreeM with the supplied @code{configure} script, there are some FreeM-specific options that may be used to compile in optional features, or exclude default ones:

@table @asis

@item @code{--enable-mwapigtk} (EXPERIMENTAL)
Enables experimental support for the M Windowing API using the GTK3 libraries. Requires that you have GTK 3 libraries, their headers, and their dependencies installed on your system.

Please consult your operating system's documentation for the correct commands to install the required libraries.

@emph{Example}

@example
$ ./configure --enable-mwapigtk
$ make
$ sudo make install
@end example

@item @code{--enable-berkeleydb} (EXPERIMENTAL)
Enables experimental support for using the BerkeleyDB database as a global handler for FreeM global namespaces. Requires that you have the @code{libdb} library, headers, and dependencies installed on your system.

Please consult your operating system's documentation for the correct commands to install the required libraries.

@emph{Example}

@example
$ ./configure --enable-berkeleydb
$ make
$ sudo make install
@end example


@item @code{--without-readline}
Builds FreeM without GNU @code{readline} support, even if @code{readline} is installed on your system.

Please note that building FreeM without GNU @code{readline} will also exclude REPL functionality and all direct-mode utility commands, i.e. @code{events}, @code{tdump}, @code{shmstat}, and @code{shmpages}.

@emph{Example}

@example
$ ./configure --without-readline
$ make
$ sudo make install
@end example


@end table

@node Accessing FreeM from C Programs
@chapter Accessing FreeM from C Programs

FreeM provides a library, @file{libfreem.so}, as well as corresponding header file @file{freem.h}, allowing C programmers to write programs that access FreeM globals, locals, structured system variables, subroutines, and extrinsic functions. This functionality can be used to implement language bindings and data access drivers for external systems.

In order to be used in your C programs, your C programs must link with @file{libfreem.so} and include @file{freem.h}. This will allow your C code access to the function prototypes, data structures, and constants required for calling the @file{libfreem.so} APIs.

You must exercise caution in developing programs that interface with FreeM through @file{libfreem.so} to ensure that all @file{libfreem.so} API calls are serialized, as FreeM and the @file{libfreem.so} library are neither thread-safe nor reentrant.

You must also avoid setting signal handlers for @code{SIGALRM}, as FreeM uses @code{SIGALRM} to manage timeouts for @command{LOCK}, @command{READ}, and @command{WRITE}.

@section freem_ref_t Data Structure
@cindex libfreem, data structures: freem_ref_t

The @code{libfreem} API uses a @code{struct} of type @code{freem_ref_t} in order to communicate state, pass in values, and return results.

The data structure, defined in @file{freem.h}, looks like this:

@verbatim
typedef struct freem_ref_t {

    /*
     * The 'reftype' field can be one of:
     * 
     *  MREF_RT_LOCAL
     *  MREF_RT_GLOBAL
     *  MREF_RT_SSV
     */
    short reftype;

    /*
     * The 'name' field is the name of the local variable,
     * global variable, or SSVN (without ^ or ^$).
     */
    char name[256];    

    /*
     * Returned data goes in a string, so you've got to figure out the
     * whole M canonical number thing yourself. Good luck. :-)
     */
    char value[STRLEN];   

    short status;

    unsigned int subscript_count;
    char subscripts[255][256];

} freem_ref_t;
@end verbatim

@emph{freem_ref_t Members}

@table @asis
@cindex libfreem, freem_ref_t.reftype
@item @option{reftype}
The @option{reftype} member determines whether we are operating on a local variable, a global variable, or a structured system variable. It may be set to any of following constants: @code{MREF_RT_LOCAL}, @code{MREF_RT_GLOBAL}, or @code{MREF_RT_SSV}.

@cindex libfreem, freem_ref_t.name
@item @option{name}
The @option{name} member contains the name of the global, local, or SSVN to be accessed. You @emph{must not} include leading characters, such as @code{^} or @code{^$}.

@cindex libfreem, freem_ref_t.value
@item @option{value}
This member contains the value read from or the value to be written to the global, local, or SSVN.

@cindex libfreem, freem_ref_t.status
@item @option{status}
This member gives us various API status values after the API call returns. In general, this value is also returned by each API function.

@cindex libfreem, freem_ref_t.subscript_count
@item @option{subscript_count}
The number of subscripts to be passed into the API function being called. This value represents the maximum index into the first dimension of the @code{subscripts} array.

@cindex libfreem, freem_ref_t.subscripts
@item @option{subscripts}
A two-dimensional array containing the subscripts to which we are referring in this API call. 

@end table

@section freem_ent_t Data Structure
@cindex libfreem, data structures: freem_ent_t

The @code{freem_function()} and @code{freem_procedure()} APIs in @code{libfreem} use the @code{freem_ent_t} struct in order to indicate the name of the entry point being called, any arguments being passed to it, and the return value of the called function (not used for @code{freem_procedure()}).

The data structure, defined in @file{freem.h}, looks like this:

@verbatim
typedef struct freem_ent_t {

    /* name of function or procedure entry point */
    char name[256];

    /* return value */
    char value[STRLEN];

    /* value of ierr on return */
    short status;

    /* argument count and array */
    unsigned int argument_count;
    char arguments[255][256];

} freem_ent_t;
@end verbatim

@emph{freem_ent_t Members}

@table @asis

@item @option{name}
@cindex libfreem, freem_ent_t.name
The @option{name} member contains the name of the extrinsic function or procedure to be called.

@cindex libfreem, freem_ent_t.value
@item @option{value}
This member contains the value returned by the function called. Not used by @code{freem_procedure()}. 

@cindex libfreem, freem_ent_t.status
@item @option{status}
This member gives us the value of @code{ierr} after the function or procedure call returns. The possible values of @code{ierr} are listed in @code{merr.h}.

@cindex libfreem, freem_ent_t.argument_count
@item @option{argument_count}
The number of arguments to be passed into the extrinsic function or procedure being called. This value represents the maximum index into the first dimension of the @code{arguments} array.

@cindex libfreem, freem_ent_t.arguments
@item @option{arguments}
A two-dimensional array containing the arguments to be passed into the extrinsic function or procedure being called.

@end table

@section freem_init()
@cindex libfreem, freem_init()

Initializes @code{libfreem} in preparation for calling other APIs.

@emph{Synopsis}

@code{pid_t freem_init(char *environment_name, char *namespace_name);}

@emph{Parameters}

@table @asis
@item @code{environment_name}
Specifies the environment to use.
@item @code{namespace_name}
Specifies the namespace to use.
@end table

@emph{Return Values}

Returns the process ID of the @code{libfreem} process on success, or @code{-1} on failure.

@emph{Example}

This example prompts the user to enter a FreeM namespace and then attempts to initialize @code{libfreem} to use the selected namespace.

@verbatim
#include <stdio.h>
#include <string.h>
#include <freem.h>

int main(int argc, char **argv, char **envp)
{
    char namespace[256];

    /* get the namespace name to use */
    printf("Enter FreeM namespace to use: ");
    fgets(namespace, 255, stdin);

    /* remove the trailing newline */
    namespace[strcspn(buffer, "\n")] = '\0';

    /* initialize libfreem using the provided namespace */
    if(freem_init("DEFAULT", namespace) == TRUE) {
        printf("\nSuccess\n");
    }
    else {
        printf("\nFailure\n");
    }
     
    return 0;
}
@end verbatim

@section freem_version()
@cindex libfreem, freem_version()

Returns the version of FreeM in use.

@emph{Synopsis}

@code{short freem_version(char *result);}

@emph{Parameters}

@table @asis
@item @code{result}
The @code{result} parameter is a pointer to a buffer in which the FreeM version information will be returned. The caller must allocate memory for this buffer prior to calling this API. It should be at least 20 bytes in length.
@end table

@emph{Return Value}

Returns @code{0}.

@emph{Example}

This example will display the FreeM version on standard output.

@verbatim
#include <stdio.h>
#include <string.h>
#include <freem.h>

int main(int argc, char **argv, char **envp)
{
    char version[20] = {0};

    freem_init(``USER'');
    freem_version(version);

    printf(``FreeM version:  %s\n'', version);

}
@end verbatim

@section freem_set()
@cindex libfreem, freem_set()

Sets a FreeM local node, global node, or writable SSVN node. 

@emph{Synopsis}

@code{short freem_set(freem_ref_t *ref);}

@emph{Parameters}

@table @asis
@item @code{freem_ref_t}
This parameter is a pointer to a @code{freem_ref_t} struct. The caller must allocate the memory for this struct.
@end table

@emph{Return Value}

Returns @code{OK} on success, or one of the other error values defined in @code{merr.h}.

@emph{Example}

This example sets the value @code{blue} into global node @code{^car("color")}.

@verbatim
#include <stdio.h>
#include <string.h>
#include <freem.h>

int main(int argc, char **argv, char **envp)
{
    freem_ref_t ref;

    /* we're setting a global */
    ref.reftype = MREF_RT_GLOBAL;

    /* access global "car" */
    strcpy(ref.name, "car");

    /* set up the subscripts */
    ref.subscript_count = 1;
    strcpy(ref.subscripts[0], "color");
 

    /* use the USER namespace */
    freem_init("USER");

    /* write the data out */
    freem_set(&ref);
    
}
@end verbatim

@section freem_get()
@cindex libfreem, freem_get()

Retrieves a FreeM local node, global node, or writable SSVN node.

@emph{Synopsis}

@code{short freem_get(freem_ref_t *ref);}

@emph{Parameters}

@table @asis
@item @code{freem_ref_t}
This parameter is a pointer to a @code{freem_ref_t} struct. The caller must allocate the memory for this struct.
@end table

@emph{Return Value}

Returns @code{OK} on success, or one of the other error values defined in @code{merr.h}.

@emph{Example}

This example retrieves the character set of the current process.

@verbatim
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <freem.h>

int main(int argc, char **argv, char)
{
    pid_t pid;
    freem_ref_t ref;

    /* get the PID of this process */
    pid = getpid();

    /* we want to access an SSVN */
    ref.reftype = MREF_RT_SSV;
    
    /* set up the name and subscripts */
    strcpy(ref.name, "JOB");

    ref.subscript_count = 2;
    sprintf(ref.subscripts[0], "%d", pid);
    strcpy(ref.subscripts[1], "CHARACTER");

    /* initialize libfreem, using the USER namespace */
    freem_init("USER");

    /* call libfreem API */
    freem_get(&ref);

    /* output the character set info */
    printf("PID %d character set is '%s'\n", pid, ref.value);
}
@end verbatim

@section freem_kill()
@cindex libfreem, freem_kill()

Deletes a FreeM local node, global node, or killable SSVN node, as well as all of its children.

@emph{short freem_kill(freem_ref_t *ref);}

@emph{Parameters}

@table @asis
@item @code{freem_ref_t}
This parameter is a pointer to a @code{freem_ref_t} struct. The caller must allocate the memory for this struct.
@end table

@emph{Return Value}

Returns @code{OK} on success, or one of the other error values defined in @code{merr.h}.

@emph{Example}

@verbatim
#include <stdio.h>
#include <string.h>
#include <freem.h>

int main(int argc, char **argv, char **envp)
{
    freem_ref_t ref;

    /* we're killing a global node */
    ref.reftype = MREF_RT_GLOBAL;

    /* access global "car" */
    strcpy(ref.name, "car");

    /* set up the subscripts */
    ref.subscript_count = 0;

    /* use the USER namespace */
    freem_init("USER");

    /* kill the global and all its descendant subscripts */
    freem_kill(&ref);    
}
@end verbatim

@section freem_data()
@cindex libfreem, freem_data()

@section freem_order()
@cindex libfreem, freem_order()

@section freem_query()
@cindex libfreem, freem_query()

@section freem_lock()
@cindex libfreem, freem_lock()

@section freem_unlock()
@cindex libfreem, freem_unlock()

@section freem_tstart()
@cindex libfreem, freem_tstart()

@section freem_trestart()
@cindex libfreem, freem_trestart()

@section freem_trollback()
@cindex libfreem, freem_trollback()

@section freem_tlevel()
@cindex libfreem, freem_tlevel()

@section freem_tcommit()
@cindex libfreem, freem_tcommit()

@section freem_function()
@cindex libfreem, freem_function()

@section freem_procedure()
@cindex libfreem, freem_procedure()

@node FreeM Administrator
@appendix FreeM Administrator
@cindex utilities, system management
@cindex utilities, fmadm
@cindex fmadm

The @code{fmadm} utility is the preferred method of managing a FreeM installation, and will eventually replace all of the existing utilities.
Unlike the existing, legacy utilities, @code{fmadm} presents a consistent, simple interface for all FreeM management tasks, and is namespace-aware.
This appendix will document each @code{fmadm} facility as it is implemented, until all of the legacy utilities have been replaced.

The @code{fmadm} utility's functions all follow the below, consistent syntax:

@example
usage:  fmadm <action> <object> <namespace> [OPTIONS]
@end example

The @emph{action} keyword can be one of the following:

@table @emph

@item list
Lists instances of @emph{object}

@item examine
Examines a single instance of @emph{object}

@item verify
Verifies the integrity of @emph{object}

@item compact
Compacts @emph{object}

@item repair
Repairs integrity problems in @emph{object}

@item create
Creates an instance of @emph{object}

@item remove
Removes an instance of @emph{object}

@item import
Imports an @emph{object}

@item export
Exports an @emph{object}

@item backup
Creates a backup of @emph{object}

@item restore
Restores a backup of @emph{object}

@item migrate
Migrates an instance of @emph{object} from an older FreeM version to the current version

@item edit
Edits an instance of @emph{object}

@end table

The @emph{object} keyword can be one of the following:

@table @emph

@item lock
The FreeM @code{LOCK} table.

Supported actions are @code{list} and @code{remove}.

@item zallocate
The FreeM @code{ZALLOCATE} table.

No actions yet implemented.

@item journal
FreeM after-image journaling.

Supported actions are @code{examine} and @code{restore}.

The @code{examine} action will dump the after-image journal entries for the selected namespace in human-readable format.

The @code{restore} action will play after-image journals forward for the selected namespace.

@item namespace
FreeM namespaces (collections of M routines and globals).

No actions yet implemented.

@item global
The data files representing each FreeM @emph{global}.

Supported actions are @code{list}, @code{examine}, @code{remove}, and @code{verify}.

@item routine
An M routine, stored as a @code{.m} file.

Supported actions are @code{list}, @code{examine}, @code{remove}, @code{import}, @code{export}, @code{backup}, and @code{edit}.

@item job
A UNIX process representing an instance of the FreeM runtime.

Supported actions are @code{list} and @code{examine}.

@end table


@node FreeM Legacy Utilities
@appendix FreeM Legacy Utilities
@cindex utilities, legacy

@section Global Compactor (gcompact)
@cindex utilities, legacy, gcompact

Compacts the specified global in place.

@emph{Syntax}

@example
gcompact @emph{/path/to/global/file}
@end example

@section Block Examiner (gfix)
@cindex utilities, gfix

The @emph{gfix} interactive utility program permits navigation of the B-tree structure of the specified global a block at a time.

@emph{Syntax}

@example
gfix @emph{</path/to/global/file>}
@end example

@section Global Repair Tool (grestore)
@cindex utilities, legacy, grestore

This utility will fix problems with the specified global.

@emph{Syntax}

@example
grestore @emph{</path/to/global/file>}
@end example

@node FreeM VIEW Commands and Functions
@appendix FreeM VIEW Commands and Functions

@section VIEW 16: Total Count of Error Messages/View Single Error Message
@cindex VIEW commands/functions, 16, total count of error messages/view single error message

Unknown semantics

@section VIEW 17: Intrinsic Z-Commands
@cindex VIEW commands/functions, 17, intrinsic Z-commands

Allows the user to retrieve or specify the list of intrinsic Z-commands that FreeM will attempt to run internally, allowing intrinsic Z-commands implemented internally to be replaced with M equivalents implemented as %-routines in the @code{SYSTEM} namespace.

@section VIEW 18: Intrinsic Z-Functions
@cindex VIEW commands/functions, 18, intrinsic Z-functions

Allows the user to retrieve or specify the list of intrinsic Z-functions that FreeM will attempt to run internally, allowing intrinsic Z-functions implemented internally to be replaced with M equivalents implemented as %-routines in the @code{SYSTEM} namespace.

@section VIEW 19: Intrinsic Special Variables
@cindex VIEW commands/functions, 19, intrinsic special variables

Allows the user to retrieve or specify which special variables are implemented internally.

@section VIEW 20: Break Service Code
@cindex VIEW commands/functions, 20, break service code

Allows the user to view or specify the code that will be run when a @code{BREAK} is encountered.

@section VIEW 21: View Size of Last Global
@cindex VIEW commands/functions, 21, view size of last global

Allows the user to view the size of the last referenced global.

@section VIEW 22: Count VIEW 22 Aliases
@cindex VIEW commands/functions, 22, count VIEW 22 aliases

Retrieves the number of VIEW 22 aliases in effect.

@section VIEW 23: View Contents of Input Buffer
@cindex VIEW commands/functions, 23, input buffer contents

Retrieves the contents of the I/O input buffer.

@section VIEW 24: Maximum Number of Screen Rows
@cindex VIEW commands/functions, 24, maximum number of screen rows

Retrieves the maximum number of screen rows supported in the current FreeM build.

@section VIEW 25: Maximum Number of Screen Columns
@cindex VIEW commands/functions, 25, maximum number of screen columns

Retrieves the maximum number of screen columns supported in the current FreeM build.

@section VIEW 26: DO/FOR/XECUTE Stack Pointer
@cindex VIEW commands/functions, 26, DO/FOR/XECUTE stack pointer

Retrieves the @code{DO}, @code{FOR}, and @code{XECUTE} stack pointer.

@section VIEW 27: DO/FOR/XECUTE Stack Pointer (On Error)
@cindex VIEW commands/functions, 27, DO/FOR/XECUTE stack pointer, on error

Retrieves the @code{DO}, @code{FOR}, and @code{XECUTE} stack pointer (on error).

@section VIEW 29: Copy Symbol Table
@cindex VIEW commands/functions, 29, copy symbol table

Copies the symbol table? We aren't currently aware of what this means.

@section VIEW 30: Inspect Arguments
@cindex VIEW commands/functions, 30, inspect arguments

Retrieves the arguments passed to the @code{freem} executable.

@section VIEW 31: Count Environment Variables
@cindex VIEW commands/functions, 31, count environment variables

Allows the user to inspect the number of variables in the process environment table.

@emph{Syntax}

@example
WRITE $VIEW(31),!
@end example

@node Implementation Limits
@appendix Implementation Limits

@cindex limitations, memory
@cindex maximum size, routine
@cindex maximum size, global
@cindex maximum size, string

@node US-ASCII Character Set
@appendix US-ASCII Character Set

@multitable {Code} {Character} 
@item Code @tab Character
@item 000 @tab @code{<NUL>}
@item 001 @tab @code{<SOH>}
@item 002 @tab @code{<STX>}
@item 003 @tab @code{<ETX>}
@item 004 @tab @code{<EOT>}
@item 005 @tab @code{<ENQ>}
@item 006 @tab @code{<ACK>}
@item 007 @tab @code{<BEL>}
@item 008 @tab @code{<BS>}
@item 009 @tab @code{<HT>}
@item 010 @tab @code{<LF>}
@item 011 @tab @code{<VT>}
@item 012 @tab @code{<FF>}
@item 013 @tab @code{<CR>}
@item 014 @tab @code{<SO>}
@item 015 @tab @code{<SI>}
@item 016 @tab @code{<DLE>}
@item 017 @tab @code{<DC1>}
@item 018 @tab @code{<DC2>}
@item 019 @tab @code{<DC3>}
@item 020 @tab @code{<DC4>}
@item 021 @tab @code{<NAK>}
@item 022 @tab @code{<SYN>}
@item 023 @tab @code{<ETB>}
@item 024 @tab @code{<CAN>}
@item 025 @tab @code{<EM>}
@item 026 @tab @code{<SUB>}
@item 027 @tab @code{<ESC>}
@item 028 @tab @code{<FS>}
@item 029 @tab @code{<GS>}
@item 030 @tab @code{<RS>}
@item 031 @tab @code{<US>}
@item 032 @tab @code{<space>}
@item 033 @tab !
@item 034 @tab ``
@item 035 @tab #


@end multitable

@node FreeM Project Coding Standards
@appendix FreeM Project Coding Standards

@section Module Headers
@cindex coding standards, module headers

Module headers should adhere to the following format (where @code{Dollar} should be replaced with a dollar sign):

@verbatim
/*
 *   DollarIdDollar
 *    Function prototypes, structs, and macros for FreeM
 *    binding library
 *
 *  
 *   Author: Serena Willis <jpw@coherent-logic.com>
 *    Copyright (C) 1998 MUG Deutschland
 *    Copyright (C) <Year> Coherent Logic Development LLC
 *
 *   This file is part of FreeM.
 *
 *   FreeM is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   FreeM is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Affero Public License for more details.
 *
 *   You should have received a copy of the GNU Affero Public License
 *   along with FreeM.  If not, see <https://www.gnu.org/licenses/>.
 *
 *   DollarLogDollar
 *
 * SPDX-FileCopyrightText:  (C) 2025 Coherent Logic Development LLC
 * SPDX-License-Identifier: AGPL-3.0-or-later
 **/
@end verbatim

@section Variable Naming
@cindex coding standards, variable naming

Variables should be named in all lowercase letters, and words within them delimited by underscores, such as @code{my_useful_variable}. @code{PascalCase} and @code{camelCase} are not to be used in this codebase under any circumstances.

Constants defined via the C preprocessor should be in all uppercase letters, with words within them likewise delimited by underscores, such as:

@verbatim
#define MY_USEFUL_CONSTANT 1
@end verbatim

@section Indentation and General Layout
@cindex coding standards, indentation
@cindex coding standards, layout

This project uses four spaces for indentation. Tabs are not to be used under any circumstances, and all source files must use a linefeed character to delineate lines. If you are working on a Windows machine, you must take care to follow this, as Windows will use a carriage return followed by a linefeed by default.

This project follows a modified version of what is known as the Stroustrup indentation style.

@section Brace Placement (Functions)
@cindex coding standards, brace placement, functions

We use modern, ANSI-style function prototypes, with the type specifier on the same line as the function name. You may encounter other styles in the code, but we are transitioning to the new style as time permits.

Below is a correct example:

@verbatim
int main(int argc, char **argv, char **envp)
{

}
@end verbatim

@section Brace Placement (if-for-while-do)
@cindex coding standards, brace placement, if-for-while-do

The @code{if} keyword should be followed by one space, then the opening paren and conditional expression. We also use Stroustrup-style @code{else} blocks, rather than the K&R 'cuddled' @code{else}:

@verbatim
if (x) {
...
}
else {
...
}

while (1) {
...
}

for (i = 1; i < 10; i++) {
...
}

do {
...
} while (x);
@end verbatim

Single-statement if blocks should be isolated to a single line:

@verbatim
if (x) stmt();
@end verbatim

not:

@verbatim
if (x)
    stmt ();
@end verbatim

Notice that there is a space between @code{if} and @code{(x)}, and also between @code{stmt} and @code{()}. This should be followed throughout the code.

If an @code{if} block has an @code{else if} or @code{else}, all parts of the construct must be bracketed, even if one or more of them contain only one statement:

@verbatim
if (x) {
    foo();
}
else if (y) {
    bar();
}
else {
    bas();
}
@end verbatim

@section Labels and goto
@cindex coding standards, labels
@cindex coding standards, goto

Labels must begin in column 1, and have two lines of vertical space above and one beneath.

@section Preprocessor Conditionals
@section coding standards, preprocessor conditionals

I have struggled with this, but have settled upon the standard practice of keeping them in column 1.

@section Overall Program Spacing
@cindex coding standards, spacing of programs

@itemize @bullet
@item
Variable declarations fall immediately beneath the opening curly brace, and should initialize the variable right there whenever initialization is used.

@item
One line between the last variable declaration and the first line of real code.

@item
The @code{return} statement of a function (when used as the last line of a function) should have one blank line above it and none below it.

@item
Really long functions (those whose entire body is longer than 24 lines) should have a comment immediately following the closing curly brace of the function, telling you what function the closing brace terminates.
@end itemize

@section The switch() Statement
@cindex coding standards, switch()

We indent @code{case} one level beneath @code{switch()}, and the code within each @code{case} beneath the @code{case}. Each @code{case} should have one line of vertical whitespace above it:

@verbatim
switch(foo) {

    case some_const:
        foo();

        break;

    case some_other_const:
        bar();

        break;	    

    default:
        exit(1);

        break;
}
@end verbatim

@section Comments
@cindex coding standards, comments

We use C-style comments (@code{/* comment */}) exclusively, even on single-line comments. C++ comments (@code{// comment}) are not permitted.

@node Index
@unnumbered Index

@printindex cp

@bye

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>