The Forms Library

The form library is a curses extension that supports easy programming of on-screen forms for data entry and program control.

The form library first appeared in AT&T System V. The version documented here is the freeware form code distributed with ncurses.

Compiling With the form Library

Your form-using modules must import the form library declarations with
	  #include <form.h>
and must be linked explicitly with the forms library using an -lform argument. Note that they must also link the ncurses library with -lncurses. Most modern linkers are two-pass and will accept either order, but it is still good practice to put -lform first and -lncurses second.

Overview of Forms

A form is a collection of fields; each field may be either a label (explanatory text) or a data-entry location. Long forms may be segmented into pages; each entry to a new page clears the screen.

To make forms, you create groups of fields and connect them with form frame objects; the form library makes this relatively simple.

Once defined, a form can be posted, that is written to an associated window. Actually, each form has two associated windows; a containing window in which the programmer can scribble titles or borders, and a subwindow in which the form fields proper are displayed.

As the form user fills out the posted form, navigation and editing keys support movement between fields, editing keys support modifying field, and plain text adds to or changes data in a current field. The form library allows you (the forms designer) to bind each navigation and editing key to any keystroke accepted by curses Fields may have validation conditions on them, so that they check input data for type and value. The form library supplies a rich set of pre-defined field types, and makes it relatively easy to define new ones.

Once its transaction is completed (or aborted), a form may be unposted (that is, undisplayed), and finally freed to make the storage associated with it and its items available for re-use.

The general flow of control of a form program looks like this:

  1. Initialize curses.
  2. Create the form fields, using new_field().
  3. Create the form using new_form().
  4. Post the form using form_post().
  5. Refresh the screen.
  6. Process user requests via an input loop.
  7. Unpost the form using form_unpost().
  8. Free the form, using free_form().
  9. Free the fields using free_field().
  10. Terminate curses.
Note that this looks much like a menu program; the form library handles tasks which are in many ways similar, and its interface was obviously designed to resemble that of the menu library wherever possible.

In forms programs, however, the `process user requests' is somewhat more complicated than for menus. Besides menu-like navigation operations, the menu driver loop has to support field editing and data validation.

Creating and Freeing Fields and Forms

The basic function for creating fields is new_field():

FIELD *new_field(int height, int width,   /* new field size */ 
                 int top, int left,       /* upper left corner */
                 int offscreen,           /* number of offscreen rows */
                 int nbuf);               /* number of working buffers */
Menu items always occupy a single row, but forms fields may have multiple rows. So new_field() requires you to specify a width and height (the first two arguments, which mist both be greater than zero).

You must also specify the location of the field's upper left corner on the screen (the third and fourth arguments, which must be zero or greater). Note that these coordinates are relative to the form subwindow, which will coincide with stdscr by default but need not be stdscr if you've done an explicit set_form_window() call.

The fifth argument allows you to specify a number of off-screen rows. If this is zero, the entire field will always be displayed. If it is nonzero, the form will be scrollable, with only one screen-full (initially the top part) displayed at any given time. If you make a field dynamic and grow it so it will no longer fit on the screen, the form will become scrollable even if the \fBoffscreen\fR argument was initially zero.

The forms library allocates one working buffer per field; the size of each buffer is ((height + offscreen)*width + 1, one character for each position in the field plus a NUL terminator. The sixth argument is the number of additional data buffers to allocate for the field; your application can use them for its own purposes.

FIELD *dup_field(FIELD *field,            /* field to copy */
                 int top, int left);      /* location of new copy */
The function dup_field() duplicates an existing field at a new location. Size and buffering information are copied; some attribute flags and status bits are not (see the form_field_new(3X) for details).

FIELD *link_field(FIELD *field,           /* field to copy */
                  int top, int left);     /* location of new copy */
The function link_field() also duplicates an existing field at a new location. The difference from dup_field() is that it arranges for the new field's buffer to be shared with the old one.

Besides the obvious use in making a field editable from two different form pages, linked fields give you a way to hack in dynamic labels. If you declare several fields linked to an original, and then make them inactive, changes from the original will still be propagated to the linked fields.

As with duplicated fields, linked fields have attribute bits separate from the original.

As you might guess, all these field-allocations return NULL if the field allocation is not possible due to an out-of-memory error or out-of-bounds arguments.

To connect fields to a form, use

FORM *new_form(FIELD **fields);
This function expects to see a NULL-terminated array of field pointers. Said fields are connected to a newly-allocated form object; its address is returned (or else NULL if the allocation fails).

Note that new_field() does not copy the pointer array into private storage; if you modify the contents of the pointer array during forms processing, all manner of bizarre things might happen. Also note that any given field may only be connected to one form.

The functions free_field() and free_form are available to free field and form objects. It is an error to attempt to free a field connected to a form, but not vice-versa; thus, you will generally free your form objects first.

Fetching and Changing Field Attributes

Each form field has a number of location and size attributes associated with it. There are other field attributes used to control display and editing of the field. Some (for example, the \fBO_STATIC\fR bit) involve sufficient complications to be covered in sections of their own later on. We cover the functions used to get and set several basic attributes here.

When a field is created, the attributes not specified by the new_field function are copied from an invisible system default field. In attribute-setting and -fetching functions, the argument NULL is taken to mean this field. Changes to it persist as defaults until your forms application terminates.

Fetching Size and Location Data

You can retrieve field sizes and locations through:

int field_info(FIELD *field,              /* field from which to fetch */
               int *height, *int width,   /* field size */ 
               int *top, int *left,       /* upper left corner */
               int *offscreen,            /* number of offscreen rows */
               int *nbuf);                /* number of working buffers */
This function is a sort of inverse of new_field(); instead of setting size and location attributes of a new field, it fetches them from an existing one.

Changing the Field Location

If is possible to move a field's location on the screen:

int move_field(FIELD *field,              /* field to alter */
               int top, int left);        /* new upper-left corner */
You can, of course. query the current location through field_info().

The Justification Attribute

One-line fields may be unjustified, justified right, justified left, or centered. Here is how you manipulate this attribute:

int set_field_just(FIELD *field,          /* field to alter */
                   int justmode);         /* mode to set */

int field_just(FIELD *field);             /* fetch mode of field */
The mode values accepted and returned by this functions are preprocessor macros NO_JUSTIFICATION, JUSTIFY_RIGHT, JUSTIFY_LEFT, or JUSTIFY_CENTER.

Field Display Attributes

For each field, you can set a foreground attribute for entered characters, a background attribute for the entire field, and a pad character for the unfilled portion of the field. You can also control pagination of the form.

This group of four field attributes controls the visual appearance of the field on the screen, without affecting in any way the data in the field buffer.

int set_field_fore(FIELD *field,          /* field to alter */
                   chtype attr);          /* attribute to set */ 

chtype field_fore(FIELD *field);          /* field to query */

int set_field_back(FIELD *field,          /* field to alter */
                   chtype attr);          /* attribute to set */ 

chtype field_back(FIELD *field);          /* field to query */

int set_field_pad(FIELD *field,           /* field to alter */
                 int pad);                /* pad character to set */ 

chtype field_pad(FIELD *field);

int set_new_page(FIELD *field,            /* field to alter */
                 int flag);               /* TRUE to force new page */ 

chtype new_page(FIELD *field);            /* field to query */
The attributes set and returned by the first four functions are normal curses(3x) display attribute values (A_STANDOUT, A_BOLD, A_REVERSE etc). The page bit of a field controls whether it is displayed at the start of a new form screen.

Field Option Bits

There is also a large collection of field option bits you can set to control various aspects of forms processing. You can manipulate them with these functions:
int set_field_opts(FIELD *field,          /* field to alter */
                   int attr);             /* attribute to set */ 

int field_opts_on(FIELD *field,           /* field to alter */
                  int attr);              /* attributes to turn on */ 

int field_opts_off(FIELD *field,          /* field to alter */
                   int attr);             /* attributes to turn off */ 

int field_opts(FIELD *field);             /* field to query */
By default, all options are on. Here are the available option bits:
O_VISIBLE
Controls whether the field is visible on the screen. Can be used during form processing to hide or pop up fields depending on the value of parent fields.
O_ACTIVE
Controls whether the field is active during forms processing (i.e. visited by form navigation keys). Can be used to make labels or derived fields with buffer values alterable by the forms application, not the user.
O_PUBLIC
Controls whether data is displayed during field entry. If this option is turned off on a field, the library will accept and edit data in that field, but it will not be displayed and the visible field cursor will not move. You can turn off the O_PUBLIC bit to define password fields.
O_EDIT
Controls whether the field's data can be modified. When this option is off, all editing requests except REQ_PREV_CHOICE and REQ_NEXT_CHOICEwill fail. Such read-only fields may be useful for help messages.
O_WRAP
Controls word-wrapping in multi-line fields. Normally, when any character of a (blank-separated) word reaches the end of the current line, the entire word is wrapped to the next line (assuming there is one). When this option is off, the word will be split across the line break.
O_BLANK
Controls field blanking. When this option is on, entering a character at the first field position erases the entire field (except for the just-entered character).
O_AUTOSKIP
Controls automatic skip to next field when this one fills. Normally, when the forms user tries to type more data into a field than will fit, the editing location jumps to next field. When this option is off, the user's cursor will hang at the end of the field. This option is ignored in dynamic fields that have not reached their size limit.
O_NULLOK
Controls whether validation is applied to blank fields. Normally, it is not; the user can leave a field blank without invoking the usual validation check on exit. If this option is off on a field, exit from it will invoke a validation check.
O_PASSOK
Controls whether validation occurs on every exit, or only after the field is modified. Normally the latter is true. Setting O_PASSOK may be useful if your field's validation function may change during forms processing.
O_STATIC
Controls whether the field is fixed to its initial dimensions. If you turn this off, the field becomes dynamic and will stretch to fit entered data.
A field's options cannot be changed while the field is currently selected. However, options may be changed on posted fields that are not current.

The option values are bit-masks and can be composed with logical-or in the obvious way.

Field Status

Every field has a status flag, which is set to FALSE when the field is created and TRUE when the value in field buffer 0 changes. This flag can be queried and set directly:

int set_field_status(FIELD *field,      /* field to alter */
                   int status);         /* mode to set */

int field_status(FIELD *field);         /* fetch mode of field */
Setting this flag under program control can be useful if you use the same form repeatedly, looking for modified fields each time.

Calling field_status() on a field not currently selected for input will return a correct value. Calling field_status() on a field that is currently selected for input may not necessarily give a correct field status value, because entered data isn't necessarily copied to buffer zero before the exit validation check. To guarantee that the returned status value reflects reality, call field_status() either (1) in the field's exit validation check routine, (2) from the field's or form's initialization or termination hooks, or (3) just after a REQ_VALIDATION request has been processed by the forms driver.

Field User Pointer

Each field structure contains one character pointer slot that is not used by the forms library. It is intended to be used by applications to store private per-field data. You can manipulate it with:
int set_field_userptr(FIELD *field,       /* field to alter */
                   char *userptr);        /* mode to set */

char *field_userptr(FIELD *field);        /* fetch mode of field */
(Properly, this user pointer field ought to have (void *) type. The (char *) type is retained for System V compatibility.)

It is valid to set the user pointer of the default field (with a set_field_userptr() call passed a NULL field pointer.) When a new field is created, the default-field user pointer is copied to initialize the new field's user pointer.

Variable-Sized Fields

Normally, a field is fixed at the size specified for it at creation time. If, however, you turn off its O_STATIC bit, it becomes dynamic and will automatically resize itself to accommodate data as it is entered. If the field has extra buffers associated with it, they will grow right along with the main input buffer.

A one-line dynamic field will have a fixed height (1) but variable width, scrolling horizontally to display data within the field area as originally dimensioned and located. A multi-line dynamic field will have a fixed width, but variable height (number of rows), scrolling vertically to display data within the field area as originally dimensioned and located.

Normally, a dynamic field is allowed to grow without limit. But it is possible to set an upper limit on the size of a dynamic field. You do it with this function:

int set_max_field(FIELD *field,     /* field to alter (may not be NULL) */
                   int max_size);   /* upper limit on field size */ 
If the field is one-line, max_size is taken to be a column size limit; if it is multi-line, it is taken to be a line size limit. To disable any limit, use an argument of zero. The growth limit can be changed whether or not the O_STATIC bit is on, but has no effect until it is.

The following properties of a field change when it becomes dynamic:

Field Validation

By default, a field will accept any data that will fit in its input buffer. However, it is possible to attach a validation type to a field. If you do this, any attempt to leave the field while it contains data that doesn't match the validation type will fail. Some validation types also have a character-validity check for each time a character is entered in the field.

A field's validation check (if any) is not called when set_field_buffer() modifies the input buffer, nor when that buffer is changed through a linked field.

The form library provides a rich set of pre-defined validation types, and gives you the capability to define custom ones of your own. You can examine and change field validation attributes with the following functions:

int set_field_type(FIELD *field,          /* field to alter */
                   FIELDTYPE *ftype,      /* type to associate */
                   ...);                  /* additional arguments*/

FIELDTYPE *field_type(FIELD *field);      /* field to query */
The validation type of a field is considered an attribute of the field. As with other field attributes, Also, doing set_field_type() with a NULL field default will change the system default for validation of newly-created fields.

Here are the pre-defined validation types:

TYPE_ALPHA

This field type accepts alphabetic data; no blanks, no digits, no special characters (this is checked at character-entry time). It is set up with:

int set_field_type(FIELD *field,          /* field to alter */
                   TYPE_ALPHA,            /* type to associate */
                   int width);            /* maximum width of field */
The width argument sets a minimum width of data. Typically you'll want to set this to the field width; if it's greater than the field width, the validation check will always fail. A minimum width of zero makes field completion optional.

TYPE_ALNUM

This field type accepts alphabetic data and digits; no blanks, no special characters (this is checked at character-entry time). It is set up with:

int set_field_type(FIELD *field,          /* field to alter */
                   TYPE_ALNUM,            /* type to associate */
                   int width);            /* maximum width of field */
The width argument sets a minimum width of data. As with TYPE_ALPHA, typically you'll want to set this to the field width; if it's greater than the field width, the validation check will always fail. A minimum width of zero makes field completion optional.

TYPE_ENUM

This type allows you to restrict a field's values to be among a specified set of string values (for example, the two-letter postal codes for U.S. states). It is set up with:

int set_field_type(FIELD *field,          /* field to alter */
                   TYPE_ENUM,             /* type to associate */
                   char **valuelist;      /* list of possible values */
                   int checkcase;         /* case-sensitive? */
                   int checkunique);      /* must specify uniquely? */
The valuelist parameter must point at a NULL-terminated list of valid strings. The checkcase argument, if true, makes comparison with the string case-sensitive.

When the user exits a TYPE_ENUM field, the validation procedure tries to complete the data in the buffer to a valid entry. If a complete choice string has been entered, it is of course valid. But it is also possible to enter a prefix of a valid string and have it completed for you.

By default, if you enter such a prefix and it matches more than one value in the string list, the prefix will be completed to the first matching value. But the checkunique argument, if true, requires prefix matches to be unique in order to be valid.

The REQ_NEXT_CHOICE and REQ_PREV_CHOICE input requests can be particularly useful with these fields.

TYPE_INTEGER

This field type accepts an integer. It is set up as follows:

int set_field_type(FIELD *field,          /* field to alter */
                   TYPE_INTEGER,          /* type to associate */
                   int padding,           /* # places to zero-pad to */
                   int vmin, int vmax);   /* valid range */
Valid characters consist of an optional leading minus and digits. The range check is performed on exit. If the range maximum is less than or equal to the minimum, the range is ignored.

If the value passes its range check, it is padded with as many leading zero digits as necessary to meet the padding argument.

A TYPE_INTEGER value buffer can conveniently be interpreted with the C library function atoi(3).

TYPE_NUMERIC

This field type accepts a decimal number. It is set up as follows:

int set_field_type(FIELD *field,          /* field to alter */
                   TYPE_NUMERIC,          /* type to associate */
                   int padding,           /* # places of precision */
                   int vmin, int vmax);   /* valid range */
Valid characters consist of an optional leading minus and digits. possibly including a decimal point. The range check is performed on exit. If the range maximum is less than or equal to the minimum, the range is ignored.

If the value passes its range check, it is padded with as many trailing zero digits as necessary to meet the padding argument.

A TYPE_NUMERIC value buffer can conveniently be interpreted with the C library function atof(3).

TYPE_REGEXP

This field type accepts data matching a regular expression. It is set up as follows:

int set_field_type(FIELD *field,          /* field to alter */
                   TYPE_REGEXP,           /* type to associate */
                   char *regexp);         /* expression to match */
The syntax for regular expressions is that of regcomp(3). The check for regular-expression match is performed on exit.

Direct Field Buffer Manipulation

The most central attribute of a field is its buffer contents. When a form has been completed, your application usually needs to know the state of each field buffer. You can find this out with:

char *field_buffer(FIELD *field,          /* field to query */
                   int bufindex);         /* number of buffer to query */
Normally, the state of the zero-numbered buffer for each field is set by the user's editing actions on that field. It's sometimes useful to be able to set the value of the zero-numbered (or some other) buffer from your application:
int set_field_buffer(FIELD *field,        /* field to alter */
                   int bufindex,          /* number of buffer to alter */
                   char *value);          /* string value to set */
If the field is not large enough and cannot be resized to a sufficiently large size to contain the specified value, the value will be truncated to fit.

Calling field_buffer() with a null field pointer will raise an error. Calling field_buffer() on a field not currently selected for input will return a correct value. Calling field_buffer() on a field that is currently selected for input may not necessarily give a correct field buffer value, because entered data isn't necessarily copied to buffer zero before the exit validation check. To guarantee that the returned buffer value reflects on-screen reality, call field_buffer() either (1) in the field's exit validation check routine, (2) from the field's or form's initialization or termination hooks, or (3) just after a REQ_VALIDATION request has been processed by the forms driver.

Attributes of Forms

As with field attributes, form attributes inherit a default from a system default form structure. These defaults can be queried or set by of these functions using a form-pointer argument of NULL.

The most important attribute of a form is its field list. You can query and change this list with:

int set_form_fields(FORM *form,           /* form to alter */
                    FIELD **fields);      /* fields to connect */

char *form_fields(FORM *form);            /* fetch fields of form */

int field_count(FORM *form);              /* count connect fields */
The second argument of set_form_fields() may be a NULL-terminated field pointer array like the one required by new_form(). In that case, the old fields of the form are disconnected but not freed (and eligible to be connected to other forms), then the new fields are connected.

It may also be null, in which case the old fields are disconnected (and not freed) but no new ones are connected.

The field_count() function simply counts the number of fields connected to a given from. It returns -1 if the form-pointer argument is NULL.

Control of Form Display

In the overview section, you saw that to display a form you normally start by defining its size (and fields), posting it, and refreshing the screen. There is an hidden step before posting, which is the association of the form with a frame window (actually, a pair of windows) within which it will be displayed. By default, the forms library associates every form with the full-screen window stdscr.

By making this step explicit, you can associate a form with a declared frame window on your screen display. This can be useful if you want to adapt the form display to different screen sizes, dynamically tile forms on the screen, or use a form as part of an interface layout managed by panels.

The two windows associated with each form have the same functions as their analogues in the menu library. Both these windows are painted when the form is posted and erased when the form is unposted.

The outer or frame window is not otherwise touched by the form routines. It exists so the programmer can associate a title, a border, or perhaps help text with the form and have it properly refreshed or erased at post/unpost time. The inner window or subwindow is where the current form page is actually displayed.

In order to declare your own frame window for a form, you'll need to know the size of the form's bounding rectangle. You can get this information with:

int scale_form(FORM *form,                /* form to query */
               int *rows,                 /* form rows */
               int *cols);                /* form cols */
The form dimensions are passed back in the locations pointed to by the arguments. Once you have this information, you can use it to declare of windows, then use one of these functions:
int set_form_win(FORM *form,              /* form to alter */
                 WINDOW *win);            /* frame window to connect */

WINDOW *form_win(FORM *form);             /* fetch frame window of form */

int set_form_sub(FORM *form,              /* form to alter */
                 WINDOW *win);            /* form subwindow to connect */

WINDOW *form_sub(FORM *form);             /* fetch form subwindow of form */
Note that curses operations, including refresh(), on the form, should be done on the frame window, not the form subwindow.

It is possible to check from your application whether all of a scrollable field is actually displayed within the menu subwindow. Use these functions:

int data_ahead(FORM *form);               /* form to be queried */ 

int data_behind(FORM *form);              /* form to be queried */ 
The function data_ahead() returns TRUE if (a) the current field is one-line and has undisplayed data off to the right, (b) the current field is multi-line and there is data off-screen below it.

The function data_behind() returns TRUE if the first (upper left hand) character position is off-screen (not being displayed).

Finally, there is a function to restore the form window's cursor to the value expected by the forms driver:

int pos_form_cursor(FORM *)               /* form to be queried */
If your application changes the form window cursor, call this function before handing control back to the forms driver in order to re-synchronize it.

Input Processing in the Forms Driver

The function form_driver() handles virtualized input requests for form navigation, editing, and validation requests, just as menu_driver does for menus (see the section on menu input handling).

int form_driver(FORM *form,               /* form to pass input to */
                int request);             /* form request code */
Your input virtualization function needs to take input and then convert it to either an alphanumeric character (which is treated as data to be entered in the currently-selected field), or a forms processing request.

The forms driver provides hooks (through input-validation and field-termination functions) with which your application code can check that the input taken by the driver matched what was expected.

Page Navigation Requests

These requests cause page-level moves through the form, triggering display of a new form screen.

REQ_NEXT_PAGE
Move to the next form page.
REQ_PREV_PAGE
Move to the previous form page.
REQ_FIRST_PAGE
Move to the first form page.
REQ_LAST_PAGE
Move to the last form page.
These requests treat the list as cyclic; that is, REQ_NEXT_PAGE from the last page goes to the first, and REQ_PREV_PAGE from the first page goes to the last.

Inter-Field Navigation Requests

These requests handle navigation between fields on the same page.

REQ_NEXT_FIELD
Move to next field.
REQ_PREV_FIELD
Move to previous field.
REQ_FIRST_FIELD
Move to the first field.
REQ_LAST_FIELD
Move to the last field.

REQ_SNEXT_FIELD
Move to sorted next field.
REQ_SPREV_FIELD
Move to sorted previous field.
REQ_SFIRST_FIELD
Move to the sorted first field.
REQ_SLAST_FIELD
Move to the sorted last field.

REQ_LEFT_FIELD
Move left to field.
REQ_RIGHT_FIELD
Move right to field.
REQ_UP_FIELD
Move up to field.
REQ_DOWN_FIELD
Move down to field.
These requests treat the list of fields on a page as cyclic; that is, REQ_NEXT_FIELD from the last field goes to the first, and REQ_PREV_FIELD from the first field goes to the last. The order of the fields for these (and the REQ_FIRST_FIELD and REQ_LAST_FIELD requests) is simply the order of the field pointers in the form array (as set up by new_form() or set_form_fields()

It is also possible to traverse the fields as if they had been sorted in screen-position order, so the sequence goes left-to-right and top-to-bottom. To do this, use the second group of four sorted-movement requests.

Finally, it is possible to move between fields using visual directions up, down, right, and left. To accomplish this, use the third group of four requests. Note, however, that the position of a form for purposes of these requests is its upper-left corner.

For example, suppose you have a multi-line field B, and two single-line fields A and C on the same line with B, with A to the left of B and C to the right of B. A REQ_MOVE_RIGHT from A will go to B only if A, B, and C all share the same first line; otherwise it will skip over B to C.

Intra-Field Navigation Requests

These requests drive movement of the edit cursor within the currently selected field.

REQ_NEXT_CHAR
Move to next character.
REQ_PREV_CHAR
Move to previous character.
REQ_NEXT_LINE
Move to next line.
REQ_PREV_LINE
Move to previous line.
REQ_NEXT_WORD
Move to next word.
REQ_PREV_WORD
Move to previous word.
REQ_BEG_FIELD
Move to beginning of field.
REQ_END_FIELD
Move to end of field.
REQ_BEG_LINE
Move to beginning of line.
REQ_END_LINE
Move to end of line.
REQ_LEFT_CHAR
Move left in field.
REQ_RIGHT_CHAR
Move right in field.
REQ_UP_CHAR
Move up in field.
REQ_DOWN_CHAR
Move down in field.
Each word is separated from the previous and next characters by whitespace. The commands to move to beginning and end of line or field look for the first or last non-pad character in their ranges.

Scrolling Requests

Fields that are dynamic and have grown and fields explicitly created with offscreen rows are scrollable. One-line fields scroll horizontally; multi-line fields scroll vertically. Most scrolling is triggered by editing and intra-field movement (the library scrolls the field to keep the cursor visible). It is possible to explicitly request scrolling with the following requests:

REQ_SCR_FLINE
Scroll vertically forward a line.
REQ_SCR_BLINE
Scroll vertically backward a line.
REQ_SCR_FPAGE
Scroll vertically forward a page.
REQ_SCR_BPAGE
Scroll vertically backward a page.
REQ_SCR_FHPAGE
Scroll vertically forward half a page.
REQ_SCR_BHPAGE
Scroll vertically backward half a page.
REQ_SCR_FCHAR
Scroll horizontally forward a character.
REQ_SCR_BCHAR
Scroll horizontally backward a character.
REQ_SCR_HFLINE
Scroll horizontally one field width forward.
REQ_SCR_HBLINE
Scroll horizontally one field width backward.
REQ_SCR_HFHALF
Scroll horizontally one half field width forward.
REQ_SCR_HBHALF
Scroll horizontally one half field width backward.
For scrolling purposes, a page of a field is the height of its visible part.

Editing Requests

When you pass the forms driver an ASCII character, it is treated as a request to add the character to the field's data buffer. Whether this is an insertion or a replacement depends on the field's edit mode (insertion is the default.

The following requests support editing the field and changing the edit mode:

REQ_INS_MODE
Set insertion mode.
REQ_OVL_MODE
Set overlay mode.
REQ_NEW_LINE
New line request (see below for explanation).
REQ_INS_CHAR
Insert space at character location.
REQ_INS_LINE
Insert blank line at character location.
REQ_DEL_CHAR
Delete character at cursor.
REQ_DEL_PREV
Delete previous word at cursor.
REQ_DEL_LINE
Delete line at cursor.
REQ_DEL_WORD
Delete word at cursor.
REQ_CLR_EOL
Clear to end of line.
REQ_CLR_EOF
Clear to end of field.
REQ_CLEAR_FIELD
Clear entire field.
The behavior of the REQ_NEW_LINE and REQ_DEL_PREV requests is complicated and partly controlled by a pair of forms options. The special cases are triggered when the cursor is at the beginning of a field, or on the last line of the field.

First, we consider REQ_NEW_LINE:

The normal behavior of REQ_NEW_LINE in insert mode is to break the current line at the position of the edit cursor, inserting the portion of the current line after the cursor as a new line following the current and moving the cursor to the beginning of that new line (you may think of this as inserting a newline in the field buffer).

The normal behavior of REQ_NEW_LINE in overlay mode is to clear the current line from the position of the edit cursor to end of line. The cursor is then moved to the beginning of the next line.

However, REQ_NEW_LINE at the beginning of a field, or on the last line of a field, instead does a REQ_NEXT_FIELD. O_NL_OVERLOAD option is off, this special action is disabled.

Now, let us consider REQ_DEL_PREV:

The normal behavior of REQ_DEL_PREV is to delete the previous character. If insert mode is on, and the cursor is at the start of a line, and the text on that line will fit on the previous one, it instead appends the contents of the current line to the previous one and deletes the current line (you may think of this as deleting a newline from the field buffer).

However, REQ_DEL_PREV at the beginning of a field is instead treated as a REQ_PREV_FIELD.

If the O_BS_OVERLOAD option is off, this special action is disabled and the forms driver just returns E_REQUEST_DENIED.

See Form Options for discussion of how to set and clear the overload options.

Order Requests

If the type of your field is ordered, and has associated functions for getting the next and previous values of the type from a given value, there are requests that can fetch that value into the field buffer:

REQ_NEXT_CHOICE
Place the successor value of the current value in the buffer.
REQ_PREV_CHOICE
Place the predecessor value of the current value in the buffer.
Of the built-in field types, only TYPE_ENUM has built-in successor and predecessor functions. When you define a field type of your own (see Custom Validation Types), you can associate our own ordering functions.

Application Commands

Form requests are represented as integers above the curses value greater than KEY_MAX and less than or equal to the constant MAX_COMMAND. If your input-virtualization routine returns a value above MAX_COMMAND, the forms driver will ignore it.

Field Change Hooks

It is possible to set function hooks to be executed whenever the current field or form changes. Here are the functions that support this:

typedef void	(*HOOK)();       /* pointer to function returning void */

int set_form_init(FORM *form,    /* form to alter */
                  HOOK hook);    /* initialization hook */

HOOK form_init(FORM *form);      /* form to query */

int set_form_term(FORM *form,    /* form to alter */
                  HOOK hook);    /* termination hook */

HOOK form_term(FORM *form);      /* form to query */

int set_field_init(FORM *form,   /* form to alter */
                  HOOK hook);    /* initialization hook */

HOOK field_init(FORM *form);     /* form to query */

int set_field_term(FORM *form,   /* form to alter */
                  HOOK hook);    /* termination hook */

HOOK field_term(FORM *form);     /* form to query */
These functions allow you to either set or query four different hooks. In each of the set functions, the second argument should be the address of a hook function. These functions differ only in the timing of the hook call.

form_init
This hook is called when the form is posted; also, just after each page change operation.
field_init
This hook is called when the form is posted; also, just after each field change
field_term
This hook is called just after field validation; that is, just before the field is altered. It is also called when the form is unposted.

form_term
This hook is called when the form is unposted; also, just before each page change operation.
Calls to these hooks may be triggered
  1. When user editing requests are processed by the forms driver
  2. When the current page is changed by set_current_field() call
  3. When the current field is changed by a set_form_page() call
See Field Change Commands for discussion of the latter two cases.

You can set a default hook for all fields by passing one of the set functions a NULL first argument.

You can disable any of these hooks by (re)setting them to NULL, the default value.

Field Change Commands

Normally, navigation through the form will be driven by the user's input requests. But sometimes it is useful to be able to move the focus for editing and viewing under control of your application, or ask which field it currently is in. The following functions help you accomplish this:

int set_current_field(FORM *form,         /* form to alter */
                      FIELD *field);      /* field to shift to */

FIELD *current_field(FORM *form);         /* form to query */

int field_index(FORM *form,               /* form to query */
                FIELD *field);            /* field to get index of */
The function field_index() returns the index of the given field in the given form's field array (the array passed to new_form() or set_form_fields()).

The initial current field of a form is the first active field on the first page. The function set_form_fields() resets this.

It is also possible to move around by pages.

int set_form_page(FORM *form,             /* form to alter */
                  int page);              /* page to go to (0-origin) */

int form_page(FORM *form);                /* return form's current page */
The initial page of a newly-created form is 0. The function set_form_fields() resets this.

Form Options

Like fields, forms may have control option bits. They can be changed or queried with these functions:

int set_form_opts(FORM *form,             /* form to alter */
                  int attr);              /* attribute to set */ 

int form_opts_on(FORM *form,              /* form to alter */
                 int attr);               /* attributes to turn on */ 

int form_opts_off(FORM *form,             /* form to alter */
                  int attr);              /* attributes to turn off */ 

int form_opts(FORM *form);                /* form to query */
By default, all options are on. Here are the available option bits:
O_NL_OVERLOAD
Enable overloading of REQ_NEW_LINE as described in Editing Requests. The value of this option is ignored on dynamic fields that have not reached their size limit; these have no last line, so the circumstances for triggering a REQ_NEXT_FIELD never arise.
O_BS_OVERLOAD
Enable overloading of REQ_DEL_PREV as described in Editing Requests.
The option values are bit-masks and can be composed with logical-or in the obvious way.

Custom Validation Types

The form library gives you the capability to define custom validation types of your own. Further, the optional additional arguments of set_field_type effectively allow you to parameterize validation types. Most of the complications in the validation-type interface have to do with the handling of the additional arguments within custom validation functions.

Union Types

The simplest way to create a custom data type is to compose it from two preexisting ones:

FIELD *link_fieldtype(FIELDTYPE *type1, 
                      FIELDTYPE *type2);
This function creates a field type that will accept any of the values legal for either of its argument field types (which may be either predefined or programmer-defined). If a set_field_type() call later requires arguments, the new composite type expects all arguments for the first type, than all arguments for the second. Order functions (see Order Requests) associated with the component types will work on the composite; what it does is check the validation function for the first type, then for the second, to figure what type the buffer contents should be treated as.

New Field Types

To create a field type from scratch, you need to specify one or both of the following things:

Here's how you do that:

typedef int (*HOOK)(); /* pointer to function returning int */

FIELDTYPE *new_fieldtype(HOOK f_validate, /* field validator */
                         HOOK c_validate) /* character validator */


int free_fieldtype(FIELDTYPE *ftype);     /* type to free */
At least one of the arguments of new_fieldtype()must be non-NULL. The forms driver will automatically call the new type's validation functions at appropriate points in processing a field of the new type.

The function free_fieldtype() deallocates the argument fieldtype, freeing all storage associated with it.

Normally, a field validator is called when the user attempts to leave the field. Its first argument is a field fointer, from which it can get to field buffer 0 and test it. If the function returns TRUE, the operation succeeds; if it returns FALSE, the edit cursor stays in the field.

A character validator gets the character passed in as a first argument. It too should return TRUE if the character is valid, FALSE otherwise.

Validation Function Arguments

Your field- and character- validation functions will be passed a second argument as well. This second argument is the address of a structure (which we'll call a pile) built from any of the field-type-specific arguments passed to set_field_type(). If no such arguments are defined for the field type, this pile pointer argument will be NULL.

In order to arrange for such arguments to be passed to your validation functions, you must associate a small set of storage-management functions with the type. The forms driver will use these to synthesize a pile from the trailing arguments of each set_field_type() argument, and a pointer to the pile will be passed to the validation functions.

Here is how you make the association:

typedef char	*(*PTRHOOK)();    /* pointer to function returning (char *) */
typedef void	(*VOIDHOOK)();    /* pointer to function returning void */

int set_fieldtype_arg(FIELDTYPE *type,    /* type to alter */
                      PTRHOOK make_str,   /* make structure from args */
                      PTRHOOK copy_str,   /* make copy of structure */
                      VOIDHOOK free_str); /* free structure storage */
Here is how the storage-management hooks are used:

make_str
This function is called by set_field_type(). It gets one argument, a va_list of the type-specific arguments passed to set_field_type(). It is expected to return a pile pointer to a data structure that encapsulates those arguments.
copy_str
This function is called by form library functions that allocate new field instances. It is expected to take a pile pointer, copy the pile to allocated storage, and return the address of the pile copy.
free_str
This function is called by field- and type-deallocation routines in the library. It takes a pile pointer argument, and is expected to free the storage of that pile.
The make_str and copy_str functions may return NULL to signal allocation failure. The library routines will that call them will return error indication when this happens. Thus, your validation functions should never see a NULL pile pointer and need not check specially for it.

Order Functions For Custom Types

Some custom field types are simply ordered in the same well-defined way that TYPE_ENUM is. For such types, it is possible to define successor and predecessor functions to support the REQ_NEXT_CHOICE and REQ_PREV_CHOICE requests. Here's how:

typedef int	(*INTHOOK)();     /* pointer to function returning int */

int set_fieldtype_arg(FIELDTYPE *type,    /* type to alter */
                      INTHOOK succ,       /* get successor value */
                      INTHOOK pred);      /* get predecessor value */
The successor and predecessor arguments will each be passed two arguments; a field pointer, and a pile pointer (as for the validation functions). They are expected to use the function field_buffer() to read the current value, and set_field_buffer() on buffer 0 to set the next or previous value. Either hook may return TRUE to indicate success (a legal next or previous value was set) or FALSE to indicate failure.

Avoiding Problems

The interface for defining custom types is complicated and tricky. Rather than attempting to create a custom type entirely from scratch, you should start by studying the library source code for whichever of the pre-defined types seems to be closest to what you want.

Use that code as a model, and evolve it towards what you really want. You will avoid many problems and annoyances that way. The code in the ncurses library has been specifically un-copyrighted to support this.

If your custom type defines order functions, have do something intuitive with a blank field. A useful convention is to make the successor of a blank field the types minimum value, and its predecessor the maximum.


THIS DOCUMENT IS STILL UNDER CONSTRUCTION. Full descriptions of the form library entry points are available in the form_*.3x manual pages included with the ncurses distributions.


Eric S. Raymond <esr@snark.thyrsus.com>