]> ncurses.scripts.mit.edu Git - ncurses.git/blob - misc/ncurses-intro.doc
ncurses 4.1
[ncurses.git] / misc / ncurses-intro.doc
1
2                          Writing Programs with NCURSES
3                                        
4      by Eric S. Raymond and Zeyd M. Ben-Halim
5      
6                                    Contents
7                                        
8      * Introduction
9           + A Brief History of Curses
10           + Scope of This Document
11           + Terminology
12      * The Curses Library
13           + An Overview of Curses
14                o Compiling Programs using Curses
15                o Updating the Screen
16                o Standard Windows and Function Naming Conventions
17                o Variables
18           + Using the Library
19                o Starting up
20                o Output
21                o Input
22                o Using Forms Characters
23                o Character Attributes and Color
24                o Mouse Interfacing
25                o Finishing Up
26           + Function Descriptions
27                o Initialization and Wrapup
28                o Causing Output to the Terminal
29                o Low-Level Capability Access
30                o Debugging
31           + Hints, Tips, and Tricks
32                o Some Notes of Caution
33                o Temporarily Leaving ncurses Mode
34                o Using ncurses under xterm
35                o Handling Multiple Terminal Screens
36                o Testing for Terminal Capabilities
37                o Tuning for Speed
38                o Special Features of ncurses
39           + Compatibility with Older Versions
40                o Refresh of Overlapping Windows
41                o Background Erase
42           + XSI Curses Conformance
43      * The Panels Library
44           + Compiling With the Panels Library
45           + Overview of Panels
46           + Panels, Input, and the Standard Screen
47           + Hiding Panels
48           + Miscellaneous Other Facilities
49      * The Menu Library
50           + Compiling with the menu Library
51           + Overview of Menus
52           + Selecting items
53           + Menu Display
54           + Menu Windows
55           + Processing Menu Input
56           + Miscellaneous Other Features
57      * The Forms Library
58           + Compiling with the forms Library
59           + Overview of Forms
60           + Creating and Freeing Fields and Forms
61           + Fetching and Changing Field Attributes
62                o Fetching Size and Location Data
63                o Changing the Field Location
64                o The Justification Attribute
65                o Field Display Attributes
66                o Field Option Bits
67                o Field Status
68                o Field User Pointer
69           + Variable-Sized Fields
70           + Field Validation
71                o TYPE_ALPHA
72                o TYPE_ALNUM
73                o TYPE_ENUM
74                o TYPE_INTEGER
75                o TYPE_NUMERIC
76                o TYPE_REGEXP
77           + Direct Field Buffer Manipulation
78           + Attributes of Forms
79           + Control of Form Display
80           + Input Processing in the Forms Driver
81                o Page Navigation Requests
82                o Inter-Field Navigation Requests
83                o Intra-Field Navigation Requests
84                o Scrolling Requests
85                o Field Editing Requests
86                o Order Requests
87                o Application Commands
88           + Field Change Hooks
89           + Field Change Commands
90           + Form Options
91           + Custom Validation Types
92                o Union Types
93                o New Field Types
94                o Validation Function Arguments
95                o Order Functions For Custom Types
96                o Avoiding Problems
97      _________________________________________________________________
98    
99                                  Introduction
100                                        
101    This document is an introduction to programming with curses. It is not
102    an exhaustive reference for the curses Application Programming
103    Interface (API); that role is filled by the curses manual pages.
104    Rather, it is intended to help C programmers ease into using the
105    package.
106    
107    This document is aimed at C applications programmers not yet
108    specifically familiar with ncurses. If you are already an experienced
109    curses programmer, you should nevertheless read the sections on Mouse
110    Interfacing, Debugging, Compatibility with Older Versions, and Hints,
111    Tips, and Tricks. These will bring you up to speed on the special
112    features and quirks of the ncurses implementation. If you are not so
113    experienced, keep reading.
114    
115    The curses package is a subroutine library for terminal-independent
116    screen-painting and input-event handling which presents a high level
117    screen model to the programmer, hiding differences between terminal
118    types and doing automatic optimization of output to change one screen
119    full of text into another. Curses uses terminfo, which is a database
120    format that can describe the capabilities of thousands of different
121    terminals.
122    
123    The curses API may seem something of an archaism on UNIX desktops
124    increasingly dominated by X, Motif, and Tcl/Tk. Nevertheless, UNIX
125    still supports tty lines and X supports xterm(1); the curses API has
126    the advantage of (a) back-portability to character-cell terminals, and
127    (b) simplicity. For an application that does not require bit-mapped
128    graphics and multiple fonts, an interface implementation using curses
129    will typically be a great deal simpler and less expensive than one
130    using an X toolkit.
131    
132 A Brief History of Curses
133
134    Historically, the first ancestor of curses was the routines written to
135    provide screen-handling for the game rogue; these used the
136    already-existing termcap database facility for describing terminal
137    capabilities. These routines were abstracted into a documented library
138    and first released with the early BSD UNIX versions.
139    
140    System III UNIX from Bell Labs featured a rewritten and much-improved
141    curses library. It introduced the terminfo format. Terminfo is based
142    on Berkeley's termcap database, but contains a number of improvements
143    and extensions. Parameterized capabilities strings were introduced,
144    making it possible to describe multiple video attributes, and colors
145    and to handle far more unusual terminals than possible with termcap.
146    In the later AT&T System V releases, curses evolved to use more
147    facilities and offer more capabilities, going far beyond BSD curses in
148    power and flexibility.
149    
150 Scope of This Document
151
152    This document describes ncurses, a freeware implementation of the
153    System V curses API with some clearly marked extensions. It includes
154    the following System V curses features:
155    
156      * Support for multiple screen highlights (BSD curses could only
157        handle one `standout' highlight, usually reverse-video).
158      * Support for line- and box-drawing using forms characters.
159      * Recognition of function keys on input.
160      * Color support.
161      * Support for pads (windows of larger than screen size on which the
162        screen or a subwindow defines a viewport).
163        
164    Also, this package makes use of the insert and delete line and
165    character features of terminals so equipped, and determines how to
166    optimally use these features with no help from the programmer. It
167    allows arbitrary combinations of video attributes to be displayed,
168    even on terminals that leave ``magic cookies'' on the screen to mark
169    changes in attributes.
170    
171    The ncurses package can also capture and use event reports from a
172    mouse in some environments (notably, xterm under the X window system).
173    This document includes tips for using the mouse.
174    
175    The ncurses package was originated by Pavel Curtis. The original
176    maintainer of the package is Zeyd Ben-Halim <zmbenhal@netcom.com>.
177    Eric S. Raymond <esr@snark.thyrsus.com> wrote many of the new features
178    in versions after 1.8.1 and wrote most of this introduction. The
179    current primary maintainers are Thomas Dickey <dickey@clark.net> and
180    Juergen Pfeifer. <Juergen.Pfeifer@T-Online.de>
181    
182    This document also describes the panels extension library, similarly
183    modeled on the SVr4 panels facility. This library allows you to
184    associate backing store with each of a stack or deck of overlapping
185    windows, and provides operations for moving windows around in the
186    stack that change their visibility in the natural way (handling window
187    overlaps).
188    
189    Finally, this document describes in detail the menus and forms
190    extension libraries, also cloned from System V, which support easy
191    construction and sequences of menus and fill-in forms. This code was
192    contributed to the project by Jürgen Pfeifer.
193    
194 Terminology
195
196    In this document, the following terminology is used with reasonable
197    consistency:
198    
199    window
200           A data structure describing a sub-rectangle of the screen
201           (possibly the entire screen). You can write to a window as
202           though it were a miniature screen, scrolling independently of
203           other windows on the physical screen.
204           
205    screens
206           A subset of windows which are as large as the terminal screen,
207           i.e., they start at the upper left hand corner and encompass
208           the lower right hand corner. One of these, stdscr, is
209           automatically provided for the programmer.
210           
211    terminal screen
212           The package's idea of what the terminal display currently looks
213           like, i.e., what the user sees now. This is a special screen.
214           
215                               The Curses Library
216                                        
217 An Overview of Curses
218
219   Compiling Programs using Curses
220   
221    In order to use the library, it is necessary to have certain types and
222    variables defined. Therefore, the programmer must have a line:
223
224           #include <curses.h>
225
226    at the top of the program source. The screen package uses the Standard
227    I/O library, so <curses.h> includes <stdio.h>. <curses.h> also
228    includes <termios.h>, <termio.h>, or <sgtty.h> depending on your
229    system. It is redundant (but harmless) for the programmer to do these
230    includes, too. In linking with curses you need to have -lncurses in
231    your LDFLAGS or on the command line. There is no need for any other
232    libraries.
233    
234   Updating the Screen
235   
236    In order to update the screen optimally, it is necessary for the
237    routines to know what the screen currently looks like and what the
238    programmer wants it to look like next. For this purpose, a data type
239    (structure) named WINDOW is defined which describes a window image to
240    the routines, including its starting position on the screen (the (y,
241    x) coordinates of the upper left hand corner) and its size. One of
242    these (called curscr, for current screen) is a screen image of what
243    the terminal currently looks like. Another screen (called stdscr, for
244    standard screen) is provided by default to make changes on.
245    
246    A window is a purely internal representation. It is used to build and
247    store a potential image of a portion of the terminal. It doesn't bear
248    any necessary relation to what is really on the terminal screen; it's
249    more like a scratchpad or write buffer.
250    
251    To make the section of physical screen corresponding to a window
252    reflect the contents of the window structure, the routine refresh()
253    (or wrefresh() if the window is not stdscr) is called.
254    
255    A given physical screen section may be within the scope of any number
256    of overlapping windows. Also, changes can be made to windows in any
257    order, without regard to motion efficiency. Then, at will, the
258    programmer can effectively say ``make it look like this,'' and let the
259    package implementation determine the most efficient way to repaint the
260    screen.
261    
262   Standard Windows and Function Naming Conventions
263   
264    As hinted above, the routines can use several windows, but two are
265    automatically given: curscr, which knows what the terminal looks like,
266    and stdscr, which is what the programmer wants the terminal to look
267    like next. The user should never actually access curscr directly.
268    Changes should be made to through the API, and then the routine
269    refresh() (or wrefresh()) called.
270    
271    Many functions are defined to use stdscr as a default screen. For
272    example, to add a character to stdscr, one calls addch() with the
273    desired character as argument. To write to a different window. use the
274    routine waddch() (for `w'indow-specific addch()) is provided. This
275    convention of prepending function names with a `w' when they are to be
276    applied to specific windows is consistent. The only routines which do
277    not follow it are those for which a window must always be specified.
278    
279    In order to move the current (y, x) coordinates from one point to
280    another, the routines move() and wmove() are provided. However, it is
281    often desirable to first move and then perform some I/O operation. In
282    order to avoid clumsiness, most I/O routines can be preceded by the
283    prefix 'mv' and the desired (y, x) coordinates prepended to the
284    arguments to the function. For example, the calls
285
286           move(y, x);
287           addch(ch);
288
289    can be replaced by
290           mvaddch(y, x, ch);
291
292    and
293           wmove(win, y, x);
294           waddch(win, ch);
295
296    can be replaced by
297           mvwaddch(win, y, x, ch);
298
299    Note that the window description pointer (win) comes before the added
300    (y, x) coordinates. If a function requires a window pointer, it is
301    always the first parameter passed.
302    
303   Variables
304   
305    The curses library sets some variables describing the terminal
306    capabilities.
307
308       type   name      description
309       ------------------------------------------------------------------
310       int    LINES     number of lines on the terminal
311       int    COLS      number of columns on the terminal
312
313    The curses.h also introduces some #define constants and types of
314    general usefulness:
315    
316    bool
317           boolean type, actually a `char' (e.g., bool doneit;)
318           
319    TRUE
320           boolean `true' flag (1).
321           
322    FALSE
323           boolean `false' flag (0).
324           
325    ERR
326           error flag returned by routines on a failure (-1).
327           
328    OK
329           error flag returned by routines when things go right.
330           
331 Using the Library
332
333    Now we describe how to actually use the screen package. In it, we
334    assume all updating, reading, etc. is applied to stdscr. These
335    instructions will work on any window, providing you change the
336    function names and parameters as mentioned above.
337    
338    Here is a sample program to motivate the discussion:
339    
340 #include <curses.h>
341 #include <signal.h>
342
343 static void finish(int sig);
344
345 main(int argc, char *argv[])
346 {
347     /* initialize your non-curses data structures here */
348
349     (void) signal(SIGINT, finish);      /* arrange interrupts to terminate */
350
351     (void) initscr();      /* initialize the curses library */
352     keypad(stdscr, TRUE);  /* enable keyboard mapping */
353     (void) nonl();         /* tell curses not to do NL->CR/NL on output */
354     (void) cbreak();       /* take input chars one at a time, no wait for \n */
355     (void) noecho();       /* don't echo input */
356
357     if (has_colors())
358     {
359         start_color();
360
361         /*
362          * Simple color assignment, often all we need.
363          */
364         init_pair(COLOR_BLACK, COLOR_BLACK, COLOR_BLACK);
365         init_pair(COLOR_GREEN, COLOR_GREEN, COLOR_BLACK);
366         init_pair(COLOR_RED, COLOR_RED, COLOR_BLACK);
367         init_pair(COLOR_CYAN, COLOR_CYAN, COLOR_BLACK);
368         init_pair(COLOR_WHITE, COLOR_WHITE, COLOR_BLACK);
369         init_pair(COLOR_MAGENTA, COLOR_MAGENTA, COLOR_BLACK);
370         init_pair(COLOR_BLUE, COLOR_BLUE, COLOR_BLACK);
371         init_pair(COLOR_YELLOW, COLOR_YELLOW, COLOR_BLACK);
372     }
373
374     for (;;)
375     {
376         int c = getch();     /* refresh, accept single keystroke of input */
377
378         /* process the command keystroke */
379     }
380
381     finish(0);               /* we're done */
382 }
383
384 static void finish(int sig)
385 {
386     endwin();
387
388     /* do your non-curses wrapup here */
389
390     exit(0);
391 }
392
393   Starting up
394   
395    In order to use the screen package, the routines must know about
396    terminal characteristics, and the space for curscr and stdscr must be
397    allocated. These function initscr() does both these things. Since it
398    must allocate space for the windows, it can overflow memory when
399    attempting to do so. On the rare occasions this happens, initscr()
400    will terminate the program with an error message. initscr() must
401    always be called before any of the routines which affect windows are
402    used. If it is not, the program will core dump as soon as either
403    curscr or stdscr are referenced. However, it is usually best to wait
404    to call it until after you are sure you will need it, like after
405    checking for startup errors. Terminal status changing routines like
406    nl() and cbreak() should be called after initscr().
407    
408    Once the screen windows have been allocated, you can set them up for
409    your program. If you want to, say, allow a screen to scroll, use
410    scrollok(). If you want the cursor to be left in place after the last
411    change, use leaveok(). If this isn't done, refresh() will move the
412    cursor to the window's current (y, x) coordinates after updating it.
413    
414    You can create new windows of your own using the functions newwin(),
415    derwin(), and subwin(). The routine delwin() will allow you to get rid
416    of old windows. All the options described above can be applied to any
417    window.
418    
419   Output
420   
421    Now that we have set things up, we will want to actually update the
422    terminal. The basic functions used to change what will go on a window
423    are addch() and move(). addch() adds a character at the current (y, x)
424    coordinates. move() changes the current (y, x) coordinates to whatever
425    you want them to be. It returns ERR if you try to move off the window.
426    As mentioned above, you can combine the two into mvaddch() to do both
427    things at once.
428    
429    The other output functions, such as addstr() and printw(), all call
430    addch() to add characters to the window.
431    
432    After you have put on the window what you want there, when you want
433    the portion of the terminal covered by the window to be made to look
434    like it, you must call refresh(). In order to optimize finding
435    changes, refresh() assumes that any part of the window not changed
436    since the last refresh() of that window has not been changed on the
437    terminal, i.e., that you have not refreshed a portion of the terminal
438    with an overlapping window. If this is not the case, the routine
439    touchwin() is provided to make it look like the entire window has been
440    changed, thus making refresh() check the whole subsection of the
441    terminal for changes.
442    
443    If you call wrefresh() with curscr as its argument, it will make the
444    screen look like curscr thinks it looks like. This is useful for
445    implementing a command which would redraw the screen in case it get
446    messed up.
447    
448   Input
449   
450    The complementary function to addch() is getch() which, if echo is
451    set, will call addch() to echo the character. Since the screen package
452    needs to know what is on the terminal at all times, if characters are
453    to be echoed, the tty must be in raw or cbreak mode. Since initially
454    the terminal has echoing enabled and is in ordinary ``cooked'' mode,
455    one or the other has to changed before calling getch(); otherwise, the
456    program's output will be unpredictable.
457    
458    When you need to accept line-oriented input in a window, the functions
459    wgetstr() and friends are available. There is even a wscanw() function
460    that can do scanf()(3)-style multi-field parsing on window input.
461    These pseudo-line-oriented functions turn on echoing while they
462    execute.
463    
464    The example code above uses the call keypad(stdscr, TRUE) to enable
465    support for function-key mapping. With this feature, the getch() code
466    watches the input stream for character sequences that correspond to
467    arrow and function keys. These sequences are returned as
468    pseudo-character values. The #define values returned are listed in the
469    curses.h The mapping from sequences to #define values is determined by
470    key_ capabilities in the terminal's terminfo entry.
471    
472   Using Forms Characters
473   
474    The addch() function (and some others, including box() and border())
475    can accept some pseudo-character arguments which are specially defined
476    by ncurses. These are #define values set up in the curses.h header;
477    see there for a complete list (look for the prefix ACS_).
478    
479    The most useful of the ACS defines are the forms-drawing characters.
480    You can use these to draw boxes and simple graphs on the screen. If
481    the terminal does not have such characters, curses.h will map them to
482    a recognizable (though ugly) set of ASCII defaults.
483    
484   Character Attributes and Color
485   
486    The ncurses package supports screen highlights including standout,
487    reverse-video, underline, and blink. It also supports color, which is
488    treated as another kind of highlight.
489    
490    Highlights are encoded, internally, as high bits of the
491    pseudo-character type (chtype) that curses.h uses to represent the
492    contents of a screen cell. See the curses.h header file for a complete
493    list of highlight mask values (look for the prefix A_).
494    
495    There are two ways to make highlights. One is to logical-or the value
496    of the highlights you want into the character argument of an addch()
497    call, or any other output call that takes a chtype argument.
498    
499    The other is to set the current-highlight value. This is logical-or'ed
500    with any highlight you specify the first way. You do this with the
501    functions attron(), attroff(), and attrset(); see the manual pages for
502    details. Color is a special kind of highlight. The package actually
503    thinks in terms of color pairs, combinations of foreground and
504    background colors. The sample code above sets up eight color pairs,
505    all of the guaranteed-available colors on black. Note that each color
506    pair is, in effect, given the name of its foreground color. Any other
507    range of eight non-conflicting values could have been used as the
508    first arguments of the init_pair() values.
509    
510    Once you've done an init_pair() that creates color-pair N, you can use
511    COLOR_PAIR(N) as a highlight that invokes that particular color
512    combination. Note that COLOR_PAIR(N), for constant N, is itself a
513    compile-time constant and can be used in initializers.
514    
515   Mouse Interfacing
516   
517    The ncurses library also provides a mouse interface. Note: his
518    facility is original to ncurses, it is not part of either the XSI
519    Curses standard, nor of System V Release 4, nor BSD curses. Thus, we
520    recommend that you wrap mouse-related code in an #ifdef using the
521    feature macro NCURSES_MOUSE_VERSION so it will not be compiled and
522    linked on non-ncurses systems.
523    
524    Presently, mouse event reporting works only under xterm. In the
525    future, ncurses will detect the presence of gpm(1), Alessandro
526    Rubini's freeware mouse server for Linux systems, and accept mouse
527    reports through it.
528    
529    The mouse interface is very simple. To activate it, you use the
530    function mousemask(), passing it as first argument a bit-mask that
531    specifies what kinds of events you want your program to be able to
532    see. It will return the bit-mask of events that actually become
533    visible, which may differ from the argument if the mouse device is not
534    capable of reporting some of the event types you specify.
535    
536    Once the mouse is active, your application's command loop should watch
537    for a return value of KEY_MOUSE from wgetch(). When you see this, a
538    mouse event report has been queued. To pick it off the queue, use the
539    function getmouse() (you must do this before the next wgetch(),
540    otherwise another mouse event might come in and make the first one
541    inaccessible).
542    
543    Each call to getmouse() fills a structure (the address of which you'll
544    pass it) with mouse event data. The event data includes zero-origin,
545    screen-relative character-cell coordinates of the mouse pointer. It
546    also includes an event mask. Bits in this mask will be set,
547    corresponding to the event type being reported.
548    
549    The mouse structure contains two additional fields which may be
550    significant in the future as ncurses interfaces to new kinds of
551    pointing device. In addition to x and y coordinates, there is a slot
552    for a z coordinate; this might be useful with touch-screens that can
553    return a pressure or duration parameter. There is also a device ID
554    field, which could be used to distinguish between multiple pointing
555    devices.
556    
557    The class of visible events may be changed at any time via
558    mousemask(). Events that can be reported include presses, releases,
559    single-, double- and triple-clicks (you can set the maximum
560    button-down time for clicks). If you don't make clicks visible, they
561    will be reported as press-release pairs. In some environments, the
562    event mask may include bits reporting the state of shift, alt, and
563    ctrl keys on the keyboard during the event.
564    
565    A function to check whether a mouse event fell within a given window
566    is also supplied. You can use this to see whether a given window
567    should consider a mouse event relevant to it.
568    
569    Because mouse event reporting will not be available in all
570    environments, it would be unwise to build ncurses applications that
571    require the use of a mouse. Rather, you should use the mouse as a
572    shortcut for point-and-shoot commands your application would normally
573    accept from the keyboard. Two of the test games in the ncurses
574    distribution (bs and knight) contain code that illustrates how this
575    can be done.
576    
577    See the manual page curs_mouse(3X) for full details of the
578    mouse-interface functions.
579    
580   Finishing Up
581   
582    In order to clean up after the ncurses routines, the routine endwin()
583    is provided. It restores tty modes to what they were when initscr()
584    was first called, and moves the cursor down to the lower-left corner.
585    Thus, anytime after the call to initscr, endwin() should be called
586    before exiting.
587    
588 Function Descriptions
589
590    We describe the detailed behavior of some important curses functions
591    here, as a supplement to the manual page descriptions.
592    
593   Initialization and Wrapup
594   
595    initscr()
596           The first function called should almost always be initscr().
597           This will determine the terminal type and initialize curses
598           data structures. initscr() also arranges that the first call to
599           refresh() will clear the screen. If an error occurs a message
600           is written to standard error and the program exits. Otherwise
601           it returns a pointer to stdscr. A few functions may be called
602           before initscr (slk_init(), filter(), ripofflines(), use_env(),
603           and, if you are using multiple terminals, newterm().)
604           
605    endwin()
606           Your program should always call endwin() before exiting or
607           shelling out of the program. This function will restore tty
608           modes, move the cursor to the lower left corner of the screen,
609           reset the terminal into the proper non-visual mode. Calling
610           refresh() or doupdate() after a temporary escape from the
611           program will restore the ncurses screen from before the escape.
612           
613    newterm(type, ofp, ifp)
614           A program which outputs to more than one terminal should use
615           newterm() instead of initscr(). newterm() should be called once
616           for each terminal. It returns a variable of type SCREEN * which
617           should be saved as a reference to that terminal. The arguments
618           are the type of the terminal (a string) and FILE pointers for
619           the output and input of the terminal. If type is NULL then the
620           environment variable $TERM is used. endwin() should called once
621           at wrapup time for each terminal opened using this function.
622           
623    set_term(new)
624           This function is used to switch to a different terminal
625           previously opened by newterm(). The screen reference for the
626           new terminal is passed as the parameter. The previous terminal
627           is returned by the function. All other calls affect only the
628           current terminal.
629           
630    delscreen(sp)
631           The inverse of newterm(); deallocates the data structures
632           associated with a given SCREEN reference.
633           
634   Causing Output to the Terminal
635   
636    refresh() and wrefresh(win)
637           These functions must be called to actually get any output on
638           the terminal, as other routines merely manipulate data
639           structures. wrefresh() copies the named window to the physical
640           terminal screen, taking into account what is already there in
641           order to do optimizations. refresh() does a refresh of
642           stdscr(). Unless leaveok() has been enabled, the physical
643           cursor of the terminal is left at the location of the window's
644           cursor.
645           
646    doupdate() and wnoutrefresh(win)
647           These two functions allow multiple updates with more efficiency
648           than wrefresh. To use them, it is important to understand how
649           curses works. In addition to all the window structures, curses
650           keeps two data structures representing the terminal screen: a
651           physical screen, describing what is actually on the screen, and
652           a virtual screen, describing what the programmer wants to have
653           on the screen. wrefresh works by first copying the named window
654           to the virtual screen (wnoutrefresh()), and then calling the
655           routine to update the screen (doupdate()). If the programmer
656           wishes to output several windows at once, a series of calls to
657           wrefresh will result in alternating calls to wnoutrefresh() and
658           doupdate(), causing several bursts of output to the screen. By
659           calling wnoutrefresh() for each window, it is then possible to
660           call doupdate() once, resulting in only one burst of output,
661           with fewer total characters transmitted (this also avoids a
662           visually annoying flicker at each update).
663           
664   Low-Level Capability Access
665   
666    setupterm(term, filenum, errret)
667           This routine is called to initialize a terminal's description,
668           without setting up the curses screen structures or changing the
669           tty-driver mode bits. term is the character string representing
670           the name of the terminal being used. filenum is the UNIX file
671           descriptor of the terminal to be used for output. errret is a
672           pointer to an integer, in which a success or failure indication
673           is returned. The values returned can be 1 (all is well), 0 (no
674           such terminal), or -1 (some problem locating the terminfo
675           database).
676           
677           The value of term can be given as NULL, which will cause the
678           value of TERM in the environment to be used. The errret pointer
679           can also be given as NULL, meaning no error code is wanted. If
680           errret is defaulted, and something goes wrong, setupterm() will
681           print an appropriate error message and exit, rather than
682           returning. Thus, a simple program can call setupterm(0, 1, 0)
683           and not worry about initialization errors.
684           
685           After the call to setupterm(), the global variable cur_term is
686           set to point to the current structure of terminal capabilities.
687           By calling setupterm() for each terminal, and saving and
688           restoring cur_term, it is possible for a program to use two or
689           more terminals at once. Setupterm() also stores the names
690           section of the terminal description in the global character
691           array ttytype[]. Subsequent calls to setupterm() will overwrite
692           this array, so you'll have to save it yourself if need be.
693           
694   Debugging
695   
696    NOTE: These functions are not part of the standard curses API!
697    
698    trace()
699           This function can be used to explicitly set a trace level. If
700           the trace level is nonzero, execution of your program will
701           generate a file called `trace' in the current working directory
702           containing a report on the library's actions. Higher trace
703           levels enable more detailed (and verbose) reporting -- see
704           comments attached to TRACE_ defines in the curses.h file for
705           details. (It is also possible to set a trace level by assigning
706           a trace level value to the environment variable NCURSES_TRACE).
707           
708    _tracef()
709           This function can be used to output your own debugging
710           information. It is only available only if you link with
711           -lncurses_g. It can be used the same way as printf(), only it
712           outputs a newline after the end of arguments. The output goes
713           to a file called trace in the current directory.
714           
715    Trace logs can be difficult to interpret due to the sheer volume of
716    data dumped in them. There is a script called tracemunch included with
717    the ncurses distribution that can alleviate this problem somewhat; it
718    compacts long sequences of similar operations into more succinct
719    single-line pseudo-operations. These pseudo-ops can be distinguished
720    by the fact that they are named in capital letters.
721    
722 Hints, Tips, and Tricks
723
724    The ncurses manual pages are a complete reference for this library. In
725    the remainder of this document, we discuss various useful methods that
726    may not be obvious from the manual page descriptions.
727    
728   Some Notes of Caution
729   
730    If you find yourself thinking you need to use noraw() or nocbreak(),
731    think again and move carefully. It's probably better design to use
732    getstr() or one of its relatives to simulate cooked mode. The noraw()
733    and nocbreak() functions try to restore cooked mode, but they may end
734    up clobbering some control bits set before you started your
735    application. Also, they have always been poorly documented, and are
736    likely to hurt your application's usability with other curses
737    libraries.
738    
739    Bear in mind that refresh() is a synonym for wrefresh(stdscr), and
740    don't try to mix use of stdscr with use of windows declared by
741    newwin(); a refresh() call will blow them off the screen. The right
742    way to handle this is to use subwin(), or not touch stdscr at all and
743    tile your screen with declared windows which you then wnoutrefresh()
744    somewhere in your program event loop, with a single doupdate() call to
745    trigger actual repainting.
746    
747    You are much less likely to run into problems if you design your
748    screen layouts to use tiled rather than overlapping windows.
749    Historically, curses support for overlapping windows has been weak,
750    fragile, and poorly documented. The ncurses library is not yet an
751    exception to this rule.
752    
753    There is a freeware panels library included in the ncurses
754    distribution that does a pretty good job of strengthening the
755    overlapping-windows facilities.
756    
757    Try to avoid using the global variables LINES and COLS. Use getmaxyx()
758    on the stdscr context instead. Reason: your code may be ported to run
759    in an environment with window resizes, in which case several screens
760    could be open with different sizes.
761    
762   Temporarily Leaving ncurses Mode
763   
764    Sometimes you will want to write a program that spends most of its
765    time in screen mode, but occasionally returns to ordinary `cooked'
766    mode. A common reason for this is to support shell-out. This behavior
767    is simple to arrange in ncurses.
768    
769    To leave ncurses mode, call endwin() as you would if you were
770    intending to terminate the program. This will take the screen back to
771    cooked mode; you can do your shell-out. When you want to return to
772    ncurses mode, simply call refresh() or doupdate(). This will repaint
773    the screen.
774    
775    There is a boolean function, isendwin(), which code can use to test
776    whether ncurses screen mode is active. It returns TRUE in the interval
777    between an endwin() call and the following refresh(), FALSE otherwise.
778    
779    Here is some sample code for shellout:
780     addstr("Shelling out...");
781     def_prog_mode();           /* save current tty modes */
782     endwin();                  /* restore original tty modes */
783     system("sh");              /* run shell */
784     addstr("returned.\n");     /* prepare return message */
785     refresh();                 /* restore save modes, repaint screen */
786
787   Using ncurses Under xterm
788   
789    A resize operation in X sends SIGWINCH to the application running
790    under xterm. The ncurses library does not catch this signal, because
791    it cannot in general know how you want the screen re-painted. You will
792    have to write the SIGWINCH handler yourself.
793    
794    The easiest way to code your SIGWINCH handler is to have it do an
795    endwin, followed by an refresh and a screen repaint you code yourself.
796    The refresh will pick up the new screen size from the xterm's
797    environment.
798    
799   Handling Multiple Terminal Screens
800   
801    The initscr() function actually calls a function named newterm() to do
802    most of its work. If you are writing a program that opens multiple
803    terminals, use newterm() directly.
804    
805    For each call, you will have to specify a terminal type and a pair of
806    file pointers; each call will return a screen reference, and stdscr
807    will be set to the last one allocated. You will switch between screens
808    with the set_term call. Note that you will also have to call
809    def_shell_mode and def_prog_mode on each tty yourself.
810    
811   Testing for Terminal Capabilities
812   
813    Sometimes you may want to write programs that test for the presence of
814    various capabilities before deciding whether to go into ncurses mode.
815    An easy way to do this is to call setupterm(), then use the functions
816    tigetflag(), tigetnum(), and tigetstr() to do your testing.
817    
818    A particularly useful case of this often comes up when you want to
819    test whether a given terminal type should be treated as `smart'
820    (cursor-addressable) or `stupid'. The right way to test this is to see
821    if the return value of tigetstr("cup") is non-NULL. Alternatively, you
822    can include the term.h file and test the value of the macro
823    cursor_address.
824    
825   Tuning for Speed
826   
827    Use the addchstr() family of functions for fast screen-painting of
828    text when you know the text doesn't contain any control characters.
829    Try to make attribute changes infrequent on your screens. Don't use
830    the immedok() option!
831    
832   Special Features of ncurses
833   
834    When running on PC-clones, ncurses has enhanced support for the IBM
835    high-half and ROM characters. The A_ALTCHARSET highlight, enables
836    display of both high-half ACS graphics and the PC ROM graphics 0-31
837    that are normally interpreted as control characters.
838    
839    The wresize() function allows you to resize a window in place.
840    
841 Compatibility with Older Versions
842
843    Despite our best efforts, there are some differences between ncurses
844    and the (undocumented!) behavior of older curses implementations.
845    These arise from ambiguities or omissions in the documentation of the
846    API.
847    
848   Refresh of Overlapping Windows
849   
850    If you define two windows A and B that overlap, and then alternately
851    scribble on and refresh them, the changes made to the overlapping
852    region under historic curses versions were often not documented
853    precisely.
854    
855    To understand why this is a problem, remember that screen updates are
856    calculated between two representations of the entire display. The
857    documentation says that when you refresh a window, it is first copied
858    to to the virtual screen, and then changes are calculated to update
859    the physical screen (and applied to the terminal). But "copied to" is
860    not very specific, and subtle differences in how copying works can
861    produce different behaviors in the case where two overlapping windows
862    are each being refreshed at unpredictable intervals.
863    
864    What happens to the overlapping region depends on what wnoutrefresh()
865    does with its argument -- what portions of the argument window it
866    copies to the virtual screen. Some implementations do "change copy",
867    copying down only locations in the window that have changed (or been
868    marked changed with wtouchln() and friends). Some implementations do
869    "entire copy", copying all window locations to the virtual screen
870    whether or not they have changed.
871    
872    The ncurses library itself has not always been consistent on this
873    score. Due to a bug, versions 1.8.7 to 1.9.8a did entire copy.
874    Versions 1.8.6 and older, and versions 1.9.9 and newer, do change
875    copy.
876    
877    For most commercial curses implementations, it is not documented and
878    not known for sure (at least not to the ncurses maintainers) whether
879    they do change copy or entire copy. We know that System V release 3
880    curses has logic in it that looks like an attempt to do change copy,
881    but the surrounding logic and data representations are sufficiently
882    complex, and our knowledge sufficiently indirect, that it's hard to
883    know whether this is reliable. It is not clear what the SVr4
884    documentation and XSI standard intend. The XSI Curses standard barely
885    mentions wnoutrefresh(); the SVr4 documents seem to be describing
886    entire-copy, but it is possible with some effort and straining to read
887    them the other way.
888    
889    It might therefore be unwise to rely on either behavior in programs
890    that might have to be linked with other curses implementations.
891    Instead, you can do an explicit touchwin() before the wnoutrefresh()
892    call to guarantee an entire-contents copy anywhere.
893    
894    The really clean way to handle this is to use the panels library. If,
895    when you want a screen update, you do update_panels(), it will do all
896    the necessary wnoutrfresh() calls for whatever panel stacking order
897    you have defined. Then you can do one doupdate() and there will be a
898    single burst of physical I/O that will do all your updates.
899    
900   Background Erase
901   
902    If you have been using a very old versions of ncurses (1.8.7 or older)
903    you may be surprised by the behavior of the erase functions. In older
904    versions, erased areas of a window were filled with a blank modified
905    by the window's current attribute (as set by wattrset(), wattron(),
906    wattroff() and friends).
907    
908    In newer versions, this is not so. Instead, the attribute of erased
909    blanks is normal unless and until it is modified by the functions
910    bkgdset() or wbkgdset().
911    
912    This change in behavior conforms ncurses to System V Release 4 and the
913    XSI Curses standard.
914    
915 XSI Curses Conformance
916
917    The ncurses library is intended to be base-level conformant with the
918    XSI Curses standard from X/Open. Many extended-level features (in
919    fact, almost all features not directly concerned with wide characters
920    and internationalization) are also supported.
921    
922    One effect of XSI conformance is the change in behavior described
923    under "Background Erase -- Compatibility with Old Versions".
924    
925    Also, ncurses meets the XSI requirement that every macro entry point
926    have a corresponding function which may be linked (and will be
927    prototype-checked) if the macro definition is disabled with #undef.
928    
929                               The Panels Library
930                                        
931    The ncurses library by itself provides good support for screen
932    displays in which the windows are tiled (non-overlapping). In the more
933    general case that windows may overlap, you have to use a series of
934    wnoutrefresh() calls followed by a doupdate(), and be careful about
935    the order you do the window refreshes in. It has to be bottom-upwards,
936    otherwise parts of windows that should be obscured will show through.
937    
938    When your interface design is such that windows may dive deeper into
939    the visibility stack or pop to the top at runtime, the resulting
940    book-keeping can be tedious and difficult to get right. Hence the
941    panels library.
942    
943    The panel library first appeared in AT&T System V. The version
944    documented here is the freeware panel code distributed with ncurses.
945    
946 Compiling With the Panels Library
947
948    Your panels-using modules must import the panels library declarations
949    with
950
951           #include <panel.h>
952
953    and must be linked explicitly with the panels library using an -lpanel
954    argument. Note that they must also link the ncurses library with
955    -lncurses. Many linkers are two-pass and will accept either order, but
956    it is still good practice to put -lpanel first and -lncurses second.
957    
958 Overview of Panels
959
960    A panel object is a window that is implicitly treated as part of a
961    deck including all other panel objects. The deck has an implicit
962    bottom-to-top visibility order. The panels library includes an update
963    function (analogous to refresh()) that displays all panels in the deck
964    in the proper order to resolve overlaps. The standard window, stdscr,
965    is considered below all panels.
966    
967    Details on the panels functions are available in the man pages. We'll
968    just hit the highlights here.
969    
970    You create a panel from a window by calling new_panel() on a window
971    pointer. It then becomes the top of the deck. The panel's window is
972    available as the value of panel_window() called with the panel pointer
973    as argument.
974    
975    You can delete a panel (removing it from the deck) with del_panel.
976    This will not deallocate the associated window; you have to do that
977    yourself. You can replace a panel's window with a different window by
978    calling replace_window. The new window may be of different size; the
979    panel code will re-compute all overlaps. This operation doesn't change
980    the panel's position in the deck.
981    
982    To move a panel's window, use move_panel(). The mvwin() function on
983    the panel's window isn't sufficient because it doesn't update the
984    panels library's representation of where the windows are. This
985    operation leaves the panel's depth, contents, and size unchanged.
986    
987    Two functions (top_panel(), bottom_panel()) are provided for
988    rearranging the deck. The first pops its argument window to the top of
989    the deck; the second sends it to the bottom. Either operation leaves
990    the panel's screen location, contents, and size unchanged.
991    
992    The function update_panels() does all the wnoutrefresh() calls needed
993    to prepare for doupdate() (which you must call yourself, afterwards).
994    
995    Typically, you will want to call update_panels() and doupdate() just
996    before accepting command input, once in each cycle of interaction with
997    the user. If you call update_panels() after each and every panel
998    write, you'll generate a lot of unnecessary refresh activity and
999    screen flicker.
1000    
1001 Panels, Input, and the Standard Screen
1002
1003    You shouldn't mix wnoutrefresh() or wrefresh() operations with panels
1004    code; this will work only if the argument window is either in the top
1005    panel or unobscured by any other panels.
1006    
1007    The stsdcr window is a special case. It is considered below all
1008    panels. Because changes to panels may obscure parts of stdscr, though,
1009    you should call update_panels() before doupdate() even when you only
1010    change stdscr.
1011    
1012    Note that wgetch automatically calls wrefresh. Therefore, before
1013    requesting input from a panel window, you need to be sure that the
1014    panel is totally unobscured.
1015    
1016    There is presently no way to display changes to one obscured panel
1017    without repainting all panels.
1018    
1019 Hiding Panels
1020
1021    It's possible to remove a panel from the deck temporarily; use
1022    hide_panel for this. Use show_panel() to render it visible again. The
1023    predicate function panel_hidden tests whether or not a panel is
1024    hidden.
1025    
1026    The panel_update code ignores hidden panels. You cannot do top_panel()
1027    or bottom_panel on a hidden panel(). Other panels operations are
1028    applicable.
1029    
1030 Miscellaneous Other Facilities
1031
1032    It's possible to navigate the deck using the functions panel_above()
1033    and panel_below. Handed a panel pointer, they return the panel above
1034    or below that panel. Handed NULL, they return the bottom-most or
1035    top-most panel.
1036    
1037    Every panel has an associated user pointer, not used by the panel
1038    code, to which you can attach application data. See the man page
1039    documentation of set_panel_userptr() and panel_userptr for details.
1040    
1041                                The Menu Library
1042                                        
1043    A menu is a screen display that assists the user to choose some subset
1044    of a given set of items. The menu library is a curses extension that
1045    supports easy programming of menu hierarchies with a uniform but
1046    flexible interface.
1047    
1048    The menu library first appeared in AT&T System V. The version
1049    documented here is the freeware menu code distributed with ncurses.
1050    
1051 Compiling With the menu Library
1052
1053    Your menu-using modules must import the menu library declarations with
1054
1055           #include <menu.h>
1056
1057    and must be linked explicitly with the menus library using an -lmenu
1058    argument. Note that they must also link the ncurses library with
1059    -lncurses. Many linkers are two-pass and will accept either order, but
1060    it is still good practice to put -lmenu first and -lncurses second.
1061    
1062 Overview of Menus
1063
1064    The menus created by this library consist of collections of items
1065    including a name string part and a description string part. To make
1066    menus, you create groups of these items and connect them with menu
1067    frame objects.
1068    
1069    The menu can then by posted, that is written to an associated window.
1070    Actually, each menu has two associated windows; a containing window in
1071    which the programmer can scribble titles or borders, and a subwindow
1072    in which the menu items proper are displayed. If this subwindow is too
1073    small to display all the items, it will be a scrollable viewport on
1074    the collection of items.
1075    
1076    A menu may also be unposted (that is, undisplayed), and finally freed
1077    to make the storage associated with it and its items available for
1078    re-use.
1079    
1080    The general flow of control of a menu program looks like this:
1081     1. Initialize curses.
1082     2. Create the menu items, using new_item().
1083     3. Create the menu using new_menu().
1084     4. Post the menu using menu_post().
1085     5. Refresh the screen.
1086     6. Process user requests via an input loop.
1087     7. Unpost the menu using menu_unpost().
1088     8. Free the menu, using free_menu().
1089     9. Free the items using free_item().
1090    10. Terminate curses.
1091        
1092 Selecting items
1093
1094    Menus may be multi-valued or (the default) single-valued (see the
1095    manual page menu_opts(3x) to see how to change the default). Both
1096    types always have a current item.
1097    
1098    From a single-valued menu you can read the selected value simply by
1099    looking at the current item. From a multi-valued menu, you get the
1100    selected set by looping through the items applying the item_value()
1101    predicate function. Your menu-processing code can use the function
1102    set_item_value() to flag the items in the select set.
1103    
1104    Menu items can be made unselectable using set_item_opts() or
1105    item_opts_off() with the O_SELECTABLE argument. This is the only
1106    option so far defined for menus, but it is good practice to code as
1107    though other option bits might be on.
1108    
1109 Menu Display
1110
1111    The menu library calculates a minimum display size for your window,
1112    based on the following variables:
1113    
1114      * The number and maximum length of the menu items
1115      * Whether the O_ROWMAJOR option is enabled
1116      * Whether display of descriptions is enabled
1117      * Whatever menu format may have been set by the programmer
1118      * The length of the menu mark string used for highlighting selected
1119        items
1120        
1121    The function set_menu_format() allows you to set the maximum size of
1122    the viewport or menu page that will be used to display menu items. You
1123    can retrieve any format associated with a menu with menu_format(). The
1124    default format is rows=16, columns=1.
1125    
1126    The actual menu page may be smaller than the format size. This depends
1127    on the item number and size and whether O_ROWMAJOR is on. This option
1128    (on by default) causes menu items to be displayed in a `raster-scan'
1129    pattern, so that if more than one item will fit horizontally the first
1130    couple of items are side-by-side in the top row. The alternative is
1131    column-major display, which tries to put the first several items in
1132    the first column.
1133    
1134    As mentioned above, a menu format not large enough to allow all items
1135    to fit on-screen will result in a menu display that is vertically
1136    scrollable.
1137    
1138    You can scroll it with requests to the menu driver, which will be
1139    described in the section on menu input handling.
1140    
1141    Each menu has a mark string used to visually tag selected items; see
1142    the menu_mark(3x) manual page for details. The mark string length also
1143    influences the menu page size.
1144    
1145    The function scale_menu() returns the minimum display size that the
1146    menu code computes from all these factors. There are other menu
1147    display attributes including a select attribute, an attribute for
1148    selectable items, an attribute for unselectable items, and a pad
1149    character used to separate item name text from description text. These
1150    have reasonable defaults which the library allows you to change (see
1151    the menu_attribs(3x) manual page.
1152    
1153 Menu Windows
1154
1155    Each menu has, as mentioned previously, a pair of associated windows.
1156    Both these windows are painted when the menu is posted and erased when
1157    the menu is unposted.
1158    
1159    The outer or frame window is not otherwise touched by the menu
1160    routines. It exists so the programmer can associate a title, a border,
1161    or perhaps help text with the menu and have it properly refreshed or
1162    erased at post/unpost time. The inner window or subwindow is where the
1163    current menu page is displayed.
1164    
1165    By default, both windows are stdscr. You can set them with the
1166    functions in menu_win(3x).
1167    
1168    When you call menu_post(), you write the menu to its subwindow. When
1169    you call menu_unpost(), you erase the subwindow, However, neither of
1170    these actually modifies the screen. To do that, call wrefresh() or
1171    some equivalent.
1172    
1173 Processing Menu Input
1174
1175    The main loop of your menu-processing code should call menu_driver()
1176    repeatedly. The first argument of this routine is a menu pointer; the
1177    second is a menu command code. You should write an input-fetching
1178    routine that maps input characters to menu command codes, and pass its
1179    output to menu_driver(). The menu command codes are fully documented
1180    in menu_driver(3x).
1181    
1182    The simplest group of command codes is REQ_NEXT_ITEM, REQ_PREV_ITEM,
1183    REQ_FIRST_ITEM, REQ_LAST_ITEM, REQ_UP_ITEM, REQ_DOWN_ITEM,
1184    REQ_LEFT_ITEM, REQ_RIGHT_ITEM. These change the currently selected
1185    item. These requests may cause scrolling of the menu page if it only
1186    partially displayed.
1187    
1188    There are explicit requests for scrolling which also change the
1189    current item (because the select location does not change, but the
1190    item there does). These are REQ_SCR_DLINE, REQ_SCR_ULINE,
1191    REQ_SCR_DPAGE, and REQ_SCR_UPAGE.
1192    
1193    The REQ_TOGGLE_ITEM selects or deselects the current item. It is for
1194    use in multi-valued menus; if you use it with O_ONEVALUE on, you'll
1195    get an error return (E_REQUEST_DENIED).
1196    
1197    Each menu has an associated pattern buffer. The menu_driver() logic
1198    tries to accumulate printable ASCII characters passed in in that
1199    buffer; when it matches a prefix of an item name, that item (or the
1200    next matching item) is selected. If appending a character yields no
1201    new match, that character is deleted from the pattern buffer, and
1202    menu_driver() returns E_NO_MATCH.
1203    
1204    Some requests change the pattern buffer directly: REQ_CLEAR_PATTERN,
1205    REQ_BACK_PATTERN, REQ_NEXT_MATCH, REQ_PREV_MATCH. The latter two are
1206    useful when pattern buffer input matches more than one item in a
1207    multi-valued menu.
1208    
1209    Each successful scroll or item navigation request clears the pattern
1210    buffer. It is also possible to set the pattern buffer explicitly with
1211    set_menu_pattern().
1212    
1213    Finally, menu driver requests above the constant MAX_COMMAND are
1214    considered application-specific commands. The menu_driver() code
1215    ignores them and returns E_UNKNOWN_COMMAND.
1216    
1217 Miscellaneous Other Features
1218
1219    Various menu options can affect the processing and visual appearance
1220    and input processing of menus. See menu_opts(3x) for details.
1221    
1222    It is possible to change the current item from application code; this
1223    is useful if you want to write your own navigation requests. It is
1224    also possible to explicitly set the top row of the menu display. See
1225    mitem_current(3x). If your application needs to change the menu
1226    subwindow cursor for any reason, pos_menu_cursor() will restore it to
1227    the correct location for continuing menu driver processing.
1228    
1229    It is possible to set hooks to be called at menu initialization and
1230    wrapup time, and whenever the selected item changes. See
1231    menu_hook(3x).
1232    
1233    Each item, and each menu, has an associated user pointer on which you
1234    can hang application data. See mitem_userptr(3x) and menu_userptr(3x).
1235    
1236                                The Forms Library
1237                                        
1238    The form library is a curses extension that supports easy programming
1239    of on-screen forms for data entry and program control.
1240    
1241    The form library first appeared in AT&T System V. The version
1242    documented here is the freeware form code distributed with ncurses.
1243    
1244 Compiling With the form Library
1245
1246    Your form-using modules must import the form library declarations with
1247
1248           #include <form.h>
1249
1250    and must be linked explicitly with the forms library using an -lform
1251    argument. Note that they must also link the ncurses library with
1252    -lncurses. Many linkers are two-pass and will accept either order, but
1253    it is still good practice to put -lform first and -lncurses second.
1254    
1255 Overview of Forms
1256
1257    A form is a collection of fields; each field may be either a label
1258    (explanatory text) or a data-entry location. Long forms may be
1259    segmented into pages; each entry to a new page clears the screen.
1260    
1261    To make forms, you create groups of fields and connect them with form
1262    frame objects; the form library makes this relatively simple.
1263    
1264    Once defined, a form can be posted, that is written to an associated
1265    window. Actually, each form has two associated windows; a containing
1266    window in which the programmer can scribble titles or borders, and a
1267    subwindow in which the form fields proper are displayed.
1268    
1269    As the form user fills out the posted form, navigation and editing
1270    keys support movement between fields, editing keys support modifying
1271    field, and plain text adds to or changes data in a current field. The
1272    form library allows you (the forms designer) to bind each navigation
1273    and editing key to any keystroke accepted by curses Fields may have
1274    validation conditions on them, so that they check input data for type
1275    and value. The form library supplies a rich set of pre-defined field
1276    types, and makes it relatively easy to define new ones.
1277    
1278    Once its transaction is completed (or aborted), a form may be unposted
1279    (that is, undisplayed), and finally freed to make the storage
1280    associated with it and its items available for re-use.
1281    
1282    The general flow of control of a form program looks like this:
1283     1. Initialize curses.
1284     2. Create the form fields, using new_field().
1285     3. Create the form using new_form().
1286     4. Post the form using form_post().
1287     5. Refresh the screen.
1288     6. Process user requests via an input loop.
1289     7. Unpost the form using form_unpost().
1290     8. Free the form, using free_form().
1291     9. Free the fields using free_field().
1292    10. Terminate curses.
1293        
1294    Note that this looks much like a menu program; the form library
1295    handles tasks which are in many ways similar, and its interface was
1296    obviously designed to resemble that of the menu library wherever
1297    possible.
1298    
1299    In forms programs, however, the `process user requests' is somewhat
1300    more complicated than for menus. Besides menu-like navigation
1301    operations, the menu driver loop has to support field editing and data
1302    validation.
1303    
1304 Creating and Freeing Fields and Forms
1305
1306    The basic function for creating fields is new_field():
1307    
1308 FIELD *new_field(int height, int width,   /* new field size */
1309                  int top, int left,       /* upper left corner */
1310                  int offscreen,           /* number of offscreen rows */
1311                  int nbuf);               /* number of working buffers */
1312
1313    Menu items always occupy a single row, but forms fields may have
1314    multiple rows. So new_field() requires you to specify a width and
1315    height (the first two arguments, which mist both be greater than
1316    zero).
1317    
1318    You must also specify the location of the field's upper left corner on
1319    the screen (the third and fourth arguments, which must be zero or
1320    greater). Note that these coordinates are relative to the form
1321    subwindow, which will coincide with stdscr by default but need not be
1322    stdscr if you've done an explicit set_form_window() call.
1323    
1324    The fifth argument allows you to specify a number of off-screen rows.
1325    If this is zero, the entire field will always be displayed. If it is
1326    nonzero, the form will be scrollable, with only one screen-full
1327    (initially the top part) displayed at any given time. If you make a
1328    field dynamic and grow it so it will no longer fit on the screen, the
1329    form will become scrollable even if the offscreen argument was
1330    initially zero.
1331    
1332    The forms library allocates one working buffer per field; the size of
1333    each buffer is ((height + offscreen)*width + 1, one character for each
1334    position in the field plus a NUL terminator. The sixth argument is the
1335    number of additional data buffers to allocate for the field; your
1336    application can use them for its own purposes.
1337    
1338 FIELD *dup_field(FIELD *field,            /* field to copy */
1339                  int top, int left);      /* location of new copy */
1340
1341    The function dup_field() duplicates an existing field at a new
1342    location. Size and buffering information are copied; some attribute
1343    flags and status bits are not (see the form_field_new(3X) for
1344    details).
1345    
1346 FIELD *link_field(FIELD *field,           /* field to copy */
1347                   int top, int left);     /* location of new copy */
1348
1349    The function link_field() also duplicates an existing field at a new
1350    location. The difference from dup_field() is that it arranges for the
1351    new field's buffer to be shared with the old one.
1352    
1353    Besides the obvious use in making a field editable from two different
1354    form pages, linked fields give you a way to hack in dynamic labels. If
1355    you declare several fields linked to an original, and then make them
1356    inactive, changes from the original will still be propagated to the
1357    linked fields.
1358    
1359    As with duplicated fields, linked fields have attribute bits separate
1360    from the original.
1361    
1362    As you might guess, all these field-allocations return NULL if the
1363    field allocation is not possible due to an out-of-memory error or
1364    out-of-bounds arguments.
1365    
1366    To connect fields to a form, use
1367    
1368 FORM *new_form(FIELD **fields);
1369
1370    This function expects to see a NULL-terminated array of field
1371    pointers. Said fields are connected to a newly-allocated form object;
1372    its address is returned (or else NULL if the allocation fails).
1373    
1374    Note that new_field() does not copy the pointer array into private
1375    storage; if you modify the contents of the pointer array during forms
1376    processing, all manner of bizarre things might happen. Also note that
1377    any given field may only be connected to one form.
1378    
1379    The functions free_field() and free_form are available to free field
1380    and form objects. It is an error to attempt to free a field connected
1381    to a form, but not vice-versa; thus, you will generally free your form
1382    objects first.
1383    
1384 Fetching and Changing Field Attributes
1385
1386    Each form field has a number of location and size attributes
1387    associated with it. There are other field attributes used to control
1388    display and editing of the field. Some (for example, the O_STATIC bit)
1389    involve sufficient complications to be covered in sections of their
1390    own later on. We cover the functions used to get and set several basic
1391    attributes here.
1392    
1393    When a field is created, the attributes not specified by the new_field
1394    function are copied from an invisible system default field. In
1395    attribute-setting and -fetching functions, the argument NULL is taken
1396    to mean this field. Changes to it persist as defaults until your forms
1397    application terminates.
1398    
1399   Fetching Size and Location Data
1400   
1401    You can retrieve field sizes and locations through:
1402    
1403 int field_info(FIELD *field,              /* field from which to fetch */
1404                int *height, *int width,   /* field size */
1405                int *top, int *left,       /* upper left corner */
1406                int *offscreen,            /* number of offscreen rows */
1407                int *nbuf);                /* number of working buffers */
1408
1409    This function is a sort of inverse of new_field(); instead of setting
1410    size and location attributes of a new field, it fetches them from an
1411    existing one.
1412    
1413   Changing the Field Location
1414   
1415    If is possible to move a field's location on the screen:
1416    
1417 int move_field(FIELD *field,              /* field to alter */
1418                int top, int left);        /* new upper-left corner */
1419
1420    You can, of course. query the current location through field_info().
1421    
1422   The Justification Attribute
1423   
1424    One-line fields may be unjustified, justified right, justified left,
1425    or centered. Here is how you manipulate this attribute:
1426    
1427 int set_field_just(FIELD *field,          /* field to alter */
1428                    int justmode);         /* mode to set */
1429
1430 int field_just(FIELD *field);             /* fetch mode of field */
1431
1432    The mode values accepted and returned by this functions are
1433    preprocessor macros NO_JUSTIFICATION, JUSTIFY_RIGHT, JUSTIFY_LEFT, or
1434    JUSTIFY_CENTER.
1435    
1436   Field Display Attributes
1437   
1438    For each field, you can set a foreground attribute for entered
1439    characters, a background attribute for the entire field, and a pad
1440    character for the unfilled portion of the field. You can also control
1441    pagination of the form.
1442    
1443    This group of four field attributes controls the visual appearance of
1444    the field on the screen, without affecting in any way the data in the
1445    field buffer.
1446    
1447 int set_field_fore(FIELD *field,          /* field to alter */
1448                    chtype attr);          /* attribute to set */
1449
1450 chtype field_fore(FIELD *field);          /* field to query */
1451
1452 int set_field_back(FIELD *field,          /* field to alter */
1453                    chtype attr);          /* attribute to set */
1454
1455 chtype field_back(FIELD *field);          /* field to query */
1456
1457 int set_field_pad(FIELD *field,           /* field to alter */
1458                  int pad);                /* pad character to set */
1459
1460 chtype field_pad(FIELD *field);
1461
1462 int set_new_page(FIELD *field,            /* field to alter */
1463                  int flag);               /* TRUE to force new page */
1464
1465 chtype new_page(FIELD *field);            /* field to query */
1466
1467    The attributes set and returned by the first four functions are normal
1468    curses(3x) display attribute values (A_STANDOUT, A_BOLD, A_REVERSE
1469    etc). The page bit of a field controls whether it is displayed at the
1470    start of a new form screen.
1471    
1472   Field Option Bits
1473   
1474    There is also a large collection of field option bits you can set to
1475    control various aspects of forms processing. You can manipulate them
1476    with these functions:
1477
1478 int set_field_opts(FIELD *field,          /* field to alter */
1479                    int attr);             /* attribute to set */
1480
1481 int field_opts_on(FIELD *field,           /* field to alter */
1482                   int attr);              /* attributes to turn on */
1483
1484 int field_opts_off(FIELD *field,          /* field to alter */
1485                    int attr);             /* attributes to turn off */
1486
1487 int field_opts(FIELD *field);             /* field to query */
1488
1489    By default, all options are on. Here are the available option bits:
1490    
1491    O_VISIBLE
1492           Controls whether the field is visible on the screen. Can be
1493           used during form processing to hide or pop up fields depending
1494           on the value of parent fields.
1495           
1496    O_ACTIVE
1497           Controls whether the field is active during forms processing
1498           (i.e. visited by form navigation keys). Can be used to make
1499           labels or derived fields with buffer values alterable by the
1500           forms application, not the user.
1501           
1502    O_PUBLIC
1503           Controls whether data is displayed during field entry. If this
1504           option is turned off on a field, the library will accept and
1505           edit data in that field, but it will not be displayed and the
1506           visible field cursor will not move. You can turn off the
1507           O_PUBLIC bit to define password fields.
1508           
1509    O_EDIT
1510           Controls whether the field's data can be modified. When this
1511           option is off, all editing requests except REQ_PREV_CHOICE and
1512           REQ_NEXT_CHOICE will fail. Such read-only fields may be useful
1513           for help messages.
1514           
1515    O_WRAP
1516           Controls word-wrapping in multi-line fields. Normally, when any
1517           character of a (blank-separated) word reaches the end of the
1518           current line, the entire word is wrapped to the next line
1519           (assuming there is one). When this option is off, the word will
1520           be split across the line break.
1521           
1522    O_BLANK
1523           Controls field blanking. When this option is on, entering a
1524           character at the first field position erases the entire field
1525           (except for the just-entered character).
1526           
1527    O_AUTOSKIP
1528           Controls automatic skip to next field when this one fills.
1529           Normally, when the forms user tries to type more data into a
1530           field than will fit, the editing location jumps to next field.
1531           When this option is off, the user's cursor will hang at the end
1532           of the field. This option is ignored in dynamic fields that
1533           have not reached their size limit.
1534           
1535    O_NULLOK
1536           Controls whether validation is applied to blank fields.
1537           Normally, it is not; the user can leave a field blank without
1538           invoking the usual validation check on exit. If this option is
1539           off on a field, exit from it will invoke a validation check.
1540           
1541    O_PASSOK
1542           Controls whether validation occurs on every exit, or only after
1543           the field is modified. Normally the latter is true. Setting
1544           O_PASSOK may be useful if your field's validation function may
1545           change during forms processing.
1546           
1547    O_STATIC
1548           Controls whether the field is fixed to its initial dimensions.
1549           If you turn this off, the field becomes dynamic and will
1550           stretch to fit entered data.
1551           
1552    A field's options cannot be changed while the field is currently
1553    selected. However, options may be changed on posted fields that are
1554    not current.
1555    
1556    The option values are bit-masks and can be composed with logical-or in
1557    the obvious way.
1558    
1559 Field Status
1560
1561    Every field has a status flag, which is set to FALSE when the field is
1562    created and TRUE when the value in field buffer 0 changes. This flag
1563    can be queried and set directly:
1564    
1565 int set_field_status(FIELD *field,      /* field to alter */
1566                    int status);         /* mode to set */
1567
1568 int field_status(FIELD *field);         /* fetch mode of field */
1569
1570    Setting this flag under program control can be useful if you use the
1571    same form repeatedly, looking for modified fields each time.
1572    
1573    Calling field_status() on a field not currently selected for input
1574    will return a correct value. Calling field_status() on a field that is
1575    currently selected for input may not necessarily give a correct field
1576    status value, because entered data isn't necessarily copied to buffer
1577    zero before the exit validation check. To guarantee that the returned
1578    status value reflects reality, call field_status() either (1) in the
1579    field's exit validation check routine, (2) from the field's or form's
1580    initialization or termination hooks, or (3) just after a
1581    REQ_VALIDATION request has been processed by the forms driver.
1582    
1583 Field User Pointer
1584
1585    Each field structure contains one character pointer slot that is not
1586    used by the forms library. It is intended to be used by applications
1587    to store private per-field data. You can manipulate it with:
1588
1589 int set_field_userptr(FIELD *field,       /* field to alter */
1590                    char *userptr);        /* mode to set */
1591
1592 char *field_userptr(FIELD *field);        /* fetch mode of field */
1593
1594    (Properly, this user pointer field ought to have (void *) type. The
1595    (char *) type is retained for System V compatibility.)
1596    
1597    It is valid to set the user pointer of the default field (with a
1598    set_field_userptr() call passed a NULL field pointer.) When a new
1599    field is created, the default-field user pointer is copied to
1600    initialize the new field's user pointer.
1601    
1602 Variable-Sized Fields
1603
1604    Normally, a field is fixed at the size specified for it at creation
1605    time. If, however, you turn off its O_STATIC bit, it becomes dynamic
1606    and will automatically resize itself to accommodate data as it is
1607    entered. If the field has extra buffers associated with it, they will
1608    grow right along with the main input buffer.
1609    
1610    A one-line dynamic field will have a fixed height (1) but variable
1611    width, scrolling horizontally to display data within the field area as
1612    originally dimensioned and located. A multi-line dynamic field will
1613    have a fixed width, but variable height (number of rows), scrolling
1614    vertically to display data within the field area as originally
1615    dimensioned and located.
1616    
1617    Normally, a dynamic field is allowed to grow without limit. But it is
1618    possible to set an upper limit on the size of a dynamic field. You do
1619    it with this function:
1620    
1621 int set_max_field(FIELD *field,     /* field to alter (may not be NULL) */
1622                    int max_size);   /* upper limit on field size */
1623
1624    If the field is one-line, max_size is taken to be a column size limit;
1625    if it is multi-line, it is taken to be a line size limit. To disable
1626    any limit, use an argument of zero. The growth limit can be changed
1627    whether or not the O_STATIC bit is on, but has no effect until it is.
1628    
1629    The following properties of a field change when it becomes dynamic:
1630      * If there is no growth limit, there is no final position of the
1631        field; therefore O_AUTOSKIP and O_NL_OVERLOAD are ignored.
1632      * Field justification will be ignored (though whatever justification
1633        is set up will be retained internally and can be queried).
1634      * The dup_field() and link_field() calls copy dynamic-buffer sizes.
1635        If the O_STATIC option is set on one of a collection of links,
1636        buffer resizing will occur only when the field is edited through
1637        that link.
1638      * The call field_info() will retrieve the original static size of
1639        the field; use dynamic_field_info() to get the actual dynamic
1640        size.
1641        
1642 Field Validation
1643
1644    By default, a field will accept any data that will fit in its input
1645    buffer. However, it is possible to attach a validation type to a
1646    field. If you do this, any attempt to leave the field while it
1647    contains data that doesn't match the validation type will fail. Some
1648    validation types also have a character-validity check for each time a
1649    character is entered in the field.
1650    
1651    A field's validation check (if any) is not called when
1652    set_field_buffer() modifies the input buffer, nor when that buffer is
1653    changed through a linked field.
1654    
1655    The form library provides a rich set of pre-defined validation types,
1656    and gives you the capability to define custom ones of your own. You
1657    can examine and change field validation attributes with the following
1658    functions:
1659    
1660 int set_field_type(FIELD *field,          /* field to alter */
1661                    FIELDTYPE *ftype,      /* type to associate */
1662                    ...);                  /* additional arguments*/
1663
1664 FIELDTYPE *field_type(FIELD *field);      /* field to query */
1665
1666    The validation type of a field is considered an attribute of the
1667    field. As with other field attributes, Also, doing set_field_type()
1668    with a NULL field default will change the system default for
1669    validation of newly-created fields.
1670    
1671    Here are the pre-defined validation types:
1672    
1673   TYPE_ALPHA
1674   
1675    This field type accepts alphabetic data; no blanks, no digits, no
1676    special characters (this is checked at character-entry time). It is
1677    set up with:
1678    
1679 int set_field_type(FIELD *field,          /* field to alter */
1680                    TYPE_ALPHA,            /* type to associate */
1681                    int width);            /* maximum width of field */
1682
1683    The width argument sets a minimum width of data. Typically you'll want
1684    to set this to the field width; if it's greater than the field width,
1685    the validation check will always fail. A minimum width of zero makes
1686    field completion optional.
1687    
1688   TYPE_ALNUM
1689   
1690    This field type accepts alphabetic data and digits; no blanks, no
1691    special characters (this is checked at character-entry time). It is
1692    set up with:
1693    
1694 int set_field_type(FIELD *field,          /* field to alter */
1695                    TYPE_ALNUM,            /* type to associate */
1696                    int width);            /* maximum width of field */
1697
1698    The width argument sets a minimum width of data. As with TYPE_ALPHA,
1699    typically you'll want to set this to the field width; if it's greater
1700    than the field width, the validation check will always fail. A minimum
1701    width of zero makes field completion optional.
1702    
1703   TYPE_ENUM
1704   
1705    This type allows you to restrict a field's values to be among a
1706    specified set of string values (for example, the two-letter postal
1707    codes for U.S. states). It is set up with:
1708    
1709 int set_field_type(FIELD *field,          /* field to alter */
1710                    TYPE_ENUM,             /* type to associate */
1711                    char **valuelist;      /* list of possible values */
1712                    int checkcase;         /* case-sensitive? */
1713                    int checkunique);      /* must specify uniquely? */
1714
1715    The valuelist parameter must point at a NULL-terminated list of valid
1716    strings. The checkcase argument, if true, makes comparison with the
1717    string case-sensitive.
1718    
1719    When the user exits a TYPE_ENUM field, the validation procedure tries
1720    to complete the data in the buffer to a valid entry. If a complete
1721    choice string has been entered, it is of course valid. But it is also
1722    possible to enter a prefix of a valid string and have it completed for
1723    you.
1724    
1725    By default, if you enter such a prefix and it matches more than one
1726    value in the string list, the prefix will be completed to the first
1727    matching value. But the checkunique argument, if true, requires prefix
1728    matches to be unique in order to be valid.
1729    
1730    The REQ_NEXT_CHOICE and REQ_PREV_CHOICE input requests can be
1731    particularly useful with these fields.
1732    
1733   TYPE_INTEGER
1734   
1735    This field type accepts an integer. It is set up as follows:
1736    
1737 int set_field_type(FIELD *field,          /* field to alter */
1738                    TYPE_INTEGER,          /* type to associate */
1739                    int padding,           /* # places to zero-pad to */
1740                    int vmin, int vmax);   /* valid range */
1741
1742    Valid characters consist of an optional leading minus and digits. The
1743    range check is performed on exit. If the range maximum is less than or
1744    equal to the minimum, the range is ignored.
1745    
1746    If the value passes its range check, it is padded with as many leading
1747    zero digits as necessary to meet the padding argument.
1748    
1749    A TYPE_INTEGER value buffer can conveniently be interpreted with the C
1750    library function atoi(3).
1751    
1752   TYPE_NUMERIC
1753   
1754    This field type accepts a decimal number. It is set up as follows:
1755    
1756 int set_field_type(FIELD *field,              /* field to alter */
1757                    TYPE_NUMERIC,              /* type to associate */
1758                    int padding,               /* # places of precision */
1759                    double vmin, double vmax); /* valid range */
1760
1761    Valid characters consist of an optional leading minus and digits.
1762    possibly including a decimal point. If your system supports locale's,
1763    the decimal point character used must be the one defined by your
1764    locale. The range check is performed on exit. If the range maximum is
1765    less than or equal to the minimum, the range is ignored.
1766    
1767    If the value passes its range check, it is padded with as many
1768    trailing zero digits as necessary to meet the padding argument.
1769    
1770    A TYPE_NUMERIC value buffer can conveniently be interpreted with the C
1771    library function atof(3).
1772    
1773   TYPE_REGEXP
1774   
1775    This field type accepts data matching a regular expression. It is set
1776    up as follows:
1777    
1778 int set_field_type(FIELD *field,          /* field to alter */
1779                    TYPE_REGEXP,           /* type to associate */
1780                    char *regexp);         /* expression to match */
1781
1782    The syntax for regular expressions is that of regcomp(3). The check
1783    for regular-expression match is performed on exit.
1784    
1785 Direct Field Buffer Manipulation
1786
1787    The chief attribute of a field is its buffer contents. When a form has
1788    been completed, your application usually needs to know the state of
1789    each field buffer. You can find this out with:
1790    
1791 char *field_buffer(FIELD *field,          /* field to query */
1792                    int bufindex);         /* number of buffer to query */
1793
1794    Normally, the state of the zero-numbered buffer for each field is set
1795    by the user's editing actions on that field. It's sometimes useful to
1796    be able to set the value of the zero-numbered (or some other) buffer
1797    from your application:
1798
1799 int set_field_buffer(FIELD *field,        /* field to alter */
1800                    int bufindex,          /* number of buffer to alter */
1801                    char *value);          /* string value to set */
1802
1803    If the field is not large enough and cannot be resized to a
1804    sufficiently large size to contain the specified value, the value will
1805    be truncated to fit.
1806    
1807    Calling field_buffer() with a null field pointer will raise an error.
1808    Calling field_buffer() on a field not currently selected for input
1809    will return a correct value. Calling field_buffer() on a field that is
1810    currently selected for input may not necessarily give a correct field
1811    buffer value, because entered data isn't necessarily copied to buffer
1812    zero before the exit validation check. To guarantee that the returned
1813    buffer value reflects on-screen reality, call field_buffer() either
1814    (1) in the field's exit validation check routine, (2) from the field's
1815    or form's initialization or termination hooks, or (3) just after a
1816    REQ_VALIDATION request has been processed by the forms driver.
1817    
1818 Attributes of Forms
1819
1820    As with field attributes, form attributes inherit a default from a
1821    system default form structure. These defaults can be queried or set by
1822    of these functions using a form-pointer argument of NULL.
1823    
1824    The principal attribute of a form is its field list. You can query and
1825    change this list with:
1826    
1827 int set_form_fields(FORM *form,           /* form to alter */
1828                     FIELD **fields);      /* fields to connect */
1829
1830 char *form_fields(FORM *form);            /* fetch fields of form */
1831
1832 int field_count(FORM *form);              /* count connect fields */
1833
1834    The second argument of set_form_fields() may be a NULL-terminated
1835    field pointer array like the one required by new_form(). In that case,
1836    the old fields of the form are disconnected but not freed (and
1837    eligible to be connected to other forms), then the new fields are
1838    connected.
1839    
1840    It may also be null, in which case the old fields are disconnected
1841    (and not freed) but no new ones are connected.
1842    
1843    The field_count() function simply counts the number of fields
1844    connected to a given from. It returns -1 if the form-pointer argument
1845    is NULL.
1846    
1847 Control of Form Display
1848
1849    In the overview section, you saw that to display a form you normally
1850    start by defining its size (and fields), posting it, and refreshing
1851    the screen. There is an hidden step before posting, which is the
1852    association of the form with a frame window (actually, a pair of
1853    windows) within which it will be displayed. By default, the forms
1854    library associates every form with the full-screen window stdscr.
1855    
1856    By making this step explicit, you can associate a form with a declared
1857    frame window on your screen display. This can be useful if you want to
1858    adapt the form display to different screen sizes, dynamically tile
1859    forms on the screen, or use a form as part of an interface layout
1860    managed by panels.
1861    
1862    The two windows associated with each form have the same functions as
1863    their analogues in the menu library. Both these windows are painted
1864    when the form is posted and erased when the form is unposted.
1865    
1866    The outer or frame window is not otherwise touched by the form
1867    routines. It exists so the programmer can associate a title, a border,
1868    or perhaps help text with the form and have it properly refreshed or
1869    erased at post/unpost time. The inner window or subwindow is where the
1870    current form page is actually displayed.
1871    
1872    In order to declare your own frame window for a form, you'll need to
1873    know the size of the form's bounding rectangle. You can get this
1874    information with:
1875    
1876 int scale_form(FORM *form,                /* form to query */
1877                int *rows,                 /* form rows */
1878                int *cols);                /* form cols */
1879
1880    The form dimensions are passed back in the locations pointed to by the
1881    arguments. Once you have this information, you can use it to declare
1882    of windows, then use one of these functions:
1883
1884 int set_form_win(FORM *form,              /* form to alter */
1885                  WINDOW *win);            /* frame window to connect */
1886
1887 WINDOW *form_win(FORM *form);             /* fetch frame window of form */
1888
1889 int set_form_sub(FORM *form,              /* form to alter */
1890                  WINDOW *win);            /* form subwindow to connect */
1891
1892 WINDOW *form_sub(FORM *form);             /* fetch form subwindow of form */
1893
1894    Note that curses operations, including refresh(), on the form, should
1895    be done on the frame window, not the form subwindow.
1896    
1897    It is possible to check from your application whether all of a
1898    scrollable field is actually displayed within the menu subwindow. Use
1899    these functions:
1900    
1901 int data_ahead(FORM *form);               /* form to be queried */
1902
1903 int data_behind(FORM *form);              /* form to be queried */
1904
1905    The function data_ahead() returns TRUE if (a) the current field is
1906    one-line and has undisplayed data off to the right, (b) the current
1907    field is multi-line and there is data off-screen below it.
1908    
1909    The function data_behind() returns TRUE if the first (upper left hand)
1910    character position is off-screen (not being displayed).
1911    
1912    Finally, there is a function to restore the form window's cursor to
1913    the value expected by the forms driver:
1914    
1915 int pos_form_cursor(FORM *)               /* form to be queried */
1916
1917    If your application changes the form window cursor, call this function
1918    before handing control back to the forms driver in order to
1919    re-synchronize it.
1920    
1921 Input Processing in the Forms Driver
1922
1923    The function form_driver() handles virtualized input requests for form
1924    navigation, editing, and validation requests, just as menu_driver does
1925    for menus (see the section on menu input handling).
1926    
1927 int form_driver(FORM *form,               /* form to pass input to */
1928                 int request);             /* form request code */
1929
1930    Your input virtualization function needs to take input and then
1931    convert it to either an alphanumeric character (which is treated as
1932    data to be entered in the currently-selected field), or a forms
1933    processing request.
1934    
1935    The forms driver provides hooks (through input-validation and
1936    field-termination functions) with which your application code can
1937    check that the input taken by the driver matched what was expected.
1938    
1939   Page Navigation Requests
1940   
1941    These requests cause page-level moves through the form, triggering
1942    display of a new form screen.
1943    
1944    REQ_NEXT_PAGE
1945           Move to the next form page.
1946           
1947    REQ_PREV_PAGE
1948           Move to the previous form page.
1949           
1950    REQ_FIRST_PAGE
1951           Move to the first form page.
1952           
1953    REQ_LAST_PAGE
1954           Move to the last form page.
1955           
1956    These requests treat the list as cyclic; that is, REQ_NEXT_PAGE from
1957    the last page goes to the first, and REQ_PREV_PAGE from the first page
1958    goes to the last.
1959    
1960   Inter-Field Navigation Requests
1961   
1962    These requests handle navigation between fields on the same page.
1963    
1964    REQ_NEXT_FIELD
1965           Move to next field.
1966           
1967    REQ_PREV_FIELD
1968           Move to previous field.
1969           
1970    REQ_FIRST_FIELD
1971           Move to the first field.
1972           
1973    REQ_LAST_FIELD
1974           Move to the last field.
1975           
1976    REQ_SNEXT_FIELD
1977           Move to sorted next field.
1978           
1979    REQ_SPREV_FIELD
1980           Move to sorted previous field.
1981           
1982    REQ_SFIRST_FIELD
1983           Move to the sorted first field.
1984           
1985    REQ_SLAST_FIELD
1986           Move to the sorted last field.
1987           
1988    REQ_LEFT_FIELD
1989           Move left to field.
1990           
1991    REQ_RIGHT_FIELD
1992           Move right to field.
1993           
1994    REQ_UP_FIELD
1995           Move up to field.
1996           
1997    REQ_DOWN_FIELD
1998           Move down to field.
1999           
2000    These requests treat the list of fields on a page as cyclic; that is,
2001    REQ_NEXT_FIELD from the last field goes to the first, and
2002    REQ_PREV_FIELD from the first field goes to the last. The order of the
2003    fields for these (and the REQ_FIRST_FIELD and REQ_LAST_FIELD requests)
2004    is simply the order of the field pointers in the form array (as set up
2005    by new_form() or set_form_fields()
2006    
2007    It is also possible to traverse the fields as if they had been sorted
2008    in screen-position order, so the sequence goes left-to-right and
2009    top-to-bottom. To do this, use the second group of four
2010    sorted-movement requests.
2011    
2012    Finally, it is possible to move between fields using visual directions
2013    up, down, right, and left. To accomplish this, use the third group of
2014    four requests. Note, however, that the position of a form for purposes
2015    of these requests is its upper-left corner.
2016    
2017    For example, suppose you have a multi-line field B, and two
2018    single-line fields A and C on the same line with B, with A to the left
2019    of B and C to the right of B. A REQ_MOVE_RIGHT from A will go to B
2020    only if A, B, and C all share the same first line; otherwise it will
2021    skip over B to C.
2022    
2023   Intra-Field Navigation Requests
2024   
2025    These requests drive movement of the edit cursor within the currently
2026    selected field.
2027    
2028    REQ_NEXT_CHAR
2029           Move to next character.
2030           
2031    REQ_PREV_CHAR
2032           Move to previous character.
2033           
2034    REQ_NEXT_LINE
2035           Move to next line.
2036           
2037    REQ_PREV_LINE
2038           Move to previous line.
2039           
2040    REQ_NEXT_WORD
2041           Move to next word.
2042           
2043    REQ_PREV_WORD
2044           Move to previous word.
2045           
2046    REQ_BEG_FIELD
2047           Move to beginning of field.
2048           
2049    REQ_END_FIELD
2050           Move to end of field.
2051           
2052    REQ_BEG_LINE
2053           Move to beginning of line.
2054           
2055    REQ_END_LINE
2056           Move to end of line.
2057           
2058    REQ_LEFT_CHAR
2059           Move left in field.
2060           
2061    REQ_RIGHT_CHAR
2062           Move right in field.
2063           
2064    REQ_UP_CHAR
2065           Move up in field.
2066           
2067    REQ_DOWN_CHAR
2068           Move down in field.
2069           
2070    Each word is separated from the previous and next characters by
2071    whitespace. The commands to move to beginning and end of line or field
2072    look for the first or last non-pad character in their ranges.
2073    
2074   Scrolling Requests
2075   
2076    Fields that are dynamic and have grown and fields explicitly created
2077    with offscreen rows are scrollable. One-line fields scroll
2078    horizontally; multi-line fields scroll vertically. Most scrolling is
2079    triggered by editing and intra-field movement (the library scrolls the
2080    field to keep the cursor visible). It is possible to explicitly
2081    request scrolling with the following requests:
2082    
2083    REQ_SCR_FLINE
2084           Scroll vertically forward a line.
2085           
2086    REQ_SCR_BLINE
2087           Scroll vertically backward a line.
2088           
2089    REQ_SCR_FPAGE
2090           Scroll vertically forward a page.
2091           
2092    REQ_SCR_BPAGE
2093           Scroll vertically backward a page.
2094           
2095    REQ_SCR_FHPAGE
2096           Scroll vertically forward half a page.
2097           
2098    REQ_SCR_BHPAGE
2099           Scroll vertically backward half a page.
2100           
2101    REQ_SCR_FCHAR
2102           Scroll horizontally forward a character.
2103           
2104    REQ_SCR_BCHAR
2105           Scroll horizontally backward a character.
2106           
2107    REQ_SCR_HFLINE
2108           Scroll horizontally one field width forward.
2109           
2110    REQ_SCR_HBLINE
2111           Scroll horizontally one field width backward.
2112           
2113    REQ_SCR_HFHALF
2114           Scroll horizontally one half field width forward.
2115           
2116    REQ_SCR_HBHALF
2117           Scroll horizontally one half field width backward.
2118           
2119    For scrolling purposes, a page of a field is the height of its visible
2120    part.
2121    
2122   Editing Requests
2123   
2124    When you pass the forms driver an ASCII character, it is treated as a
2125    request to add the character to the field's data buffer. Whether this
2126    is an insertion or a replacement depends on the field's edit mode
2127    (insertion is the default.
2128    
2129    The following requests support editing the field and changing the edit
2130    mode:
2131    
2132    REQ_INS_MODE
2133           Set insertion mode.
2134           
2135    REQ_OVL_MODE
2136           Set overlay mode.
2137           
2138    REQ_NEW_LINE
2139           New line request (see below for explanation).
2140           
2141    REQ_INS_CHAR
2142           Insert space at character location.
2143           
2144    REQ_INS_LINE
2145           Insert blank line at character location.
2146           
2147    REQ_DEL_CHAR
2148           Delete character at cursor.
2149           
2150    REQ_DEL_PREV
2151           Delete previous word at cursor.
2152           
2153    REQ_DEL_LINE
2154           Delete line at cursor.
2155           
2156    REQ_DEL_WORD
2157           Delete word at cursor.
2158           
2159    REQ_CLR_EOL
2160           Clear to end of line.
2161           
2162    REQ_CLR_EOF
2163           Clear to end of field.
2164           
2165    REQ_CLEAR_FIELD
2166           Clear entire field.
2167           
2168    The behavior of the REQ_NEW_LINE and REQ_DEL_PREV requests is
2169    complicated and partly controlled by a pair of forms options. The
2170    special cases are triggered when the cursor is at the beginning of a
2171    field, or on the last line of the field.
2172    
2173    First, we consider REQ_NEW_LINE:
2174    
2175    The normal behavior of REQ_NEW_LINE in insert mode is to break the
2176    current line at the position of the edit cursor, inserting the portion
2177    of the current line after the cursor as a new line following the
2178    current and moving the cursor to the beginning of that new line (you
2179    may think of this as inserting a newline in the field buffer).
2180    
2181    The normal behavior of REQ_NEW_LINE in overlay mode is to clear the
2182    current line from the position of the edit cursor to end of line. The
2183    cursor is then moved to the beginning of the next line.
2184    
2185    However, REQ_NEW_LINE at the beginning of a field, or on the last line
2186    of a field, instead does a REQ_NEXT_FIELD. O_NL_OVERLOAD option is
2187    off, this special action is disabled.
2188    
2189    Now, let us consider REQ_DEL_PREV:
2190    
2191    The normal behavior of REQ_DEL_PREV is to delete the previous
2192    character. If insert mode is on, and the cursor is at the start of a
2193    line, and the text on that line will fit on the previous one, it
2194    instead appends the contents of the current line to the previous one
2195    and deletes the current line (you may think of this as deleting a
2196    newline from the field buffer).
2197    
2198    However, REQ_DEL_PREV at the beginning of a field is instead treated
2199    as a REQ_PREV_FIELD.
2200    
2201    If the O_BS_OVERLOAD option is off, this special action is disabled
2202    and the forms driver just returns E_REQUEST_DENIED.
2203    
2204    See Form Options for discussion of how to set and clear the overload
2205    options.
2206    
2207   Order Requests
2208   
2209    If the type of your field is ordered, and has associated functions for
2210    getting the next and previous values of the type from a given value,
2211    there are requests that can fetch that value into the field buffer:
2212    
2213    REQ_NEXT_CHOICE
2214           Place the successor value of the current value in the buffer.
2215           
2216    REQ_PREV_CHOICE
2217           Place the predecessor value of the current value in the buffer.
2218           
2219    Of the built-in field types, only TYPE_ENUM has built-in successor and
2220    predecessor functions. When you define a field type of your own (see
2221    Custom Validation Types), you can associate our own ordering
2222    functions.
2223    
2224   Application Commands
2225   
2226    Form requests are represented as integers above the curses value
2227    greater than KEY_MAX and less than or equal to the constant
2228    MAX_COMMAND. If your input-virtualization routine returns a value
2229    above MAX_COMMAND, the forms driver will ignore it.
2230    
2231 Field Change Hooks
2232
2233    It is possible to set function hooks to be executed whenever the
2234    current field or form changes. Here are the functions that support
2235    this:
2236    
2237 typedef void    (*HOOK)();       /* pointer to function returning void */
2238
2239 int set_form_init(FORM *form,    /* form to alter */
2240                   HOOK hook);    /* initialization hook */
2241
2242 HOOK form_init(FORM *form);      /* form to query */
2243
2244 int set_form_term(FORM *form,    /* form to alter */
2245                   HOOK hook);    /* termination hook */
2246
2247 HOOK form_term(FORM *form);      /* form to query */
2248
2249 int set_field_init(FORM *form,   /* form to alter */
2250                   HOOK hook);    /* initialization hook */
2251
2252 HOOK field_init(FORM *form);     /* form to query */
2253
2254 int set_field_term(FORM *form,   /* form to alter */
2255                   HOOK hook);    /* termination hook */
2256
2257 HOOK field_term(FORM *form);     /* form to query */
2258
2259    These functions allow you to either set or query four different hooks.
2260    In each of the set functions, the second argument should be the
2261    address of a hook function. These functions differ only in the timing
2262    of the hook call.
2263    
2264    form_init
2265           This hook is called when the form is posted; also, just after
2266           each page change operation.
2267           
2268    field_init
2269           This hook is called when the form is posted; also, just after
2270           each field change
2271           
2272    field_term
2273           This hook is called just after field validation; that is, just
2274           before the field is altered. It is also called when the form is
2275           unposted.
2276           
2277    form_term
2278           This hook is called when the form is unposted; also, just
2279           before each page change operation.
2280           
2281    Calls to these hooks may be triggered
2282     1. When user editing requests are processed by the forms driver
2283     2. When the current page is changed by set_current_field() call
2284     3. When the current field is changed by a set_form_page() call
2285        
2286    See Field Change Commands for discussion of the latter two cases.
2287    
2288    You can set a default hook for all fields by passing one of the set
2289    functions a NULL first argument.
2290    
2291    You can disable any of these hooks by (re)setting them to NULL, the
2292    default value.
2293    
2294 Field Change Commands
2295
2296    Normally, navigation through the form will be driven by the user's
2297    input requests. But sometimes it is useful to be able to move the
2298    focus for editing and viewing under control of your application, or
2299    ask which field it currently is in. The following functions help you
2300    accomplish this:
2301    
2302 int set_current_field(FORM *form,         /* form to alter */
2303                       FIELD *field);      /* field to shift to */
2304
2305 FIELD *current_field(FORM *form);         /* form to query */
2306
2307 int field_index(FORM *form,               /* form to query */
2308                 FIELD *field);            /* field to get index of */
2309
2310    The function field_index() returns the index of the given field in the
2311    given form's field array (the array passed to new_form() or
2312    set_form_fields()).
2313    
2314    The initial current field of a form is the first active field on the
2315    first page. The function set_form_fields() resets this.
2316    
2317    It is also possible to move around by pages.
2318    
2319 int set_form_page(FORM *form,             /* form to alter */
2320                   int page);              /* page to go to (0-origin) */
2321
2322 int form_page(FORM *form);                /* return form's current page */
2323
2324    The initial page of a newly-created form is 0. The function
2325    set_form_fields() resets this.
2326    
2327 Form Options
2328
2329    Like fields, forms may have control option bits. They can be changed
2330    or queried with these functions:
2331    
2332 int set_form_opts(FORM *form,             /* form to alter */
2333                   int attr);              /* attribute to set */
2334
2335 int form_opts_on(FORM *form,              /* form to alter */
2336                  int attr);               /* attributes to turn on */
2337
2338 int form_opts_off(FORM *form,             /* form to alter */
2339                   int attr);              /* attributes to turn off */
2340
2341 int form_opts(FORM *form);                /* form to query */
2342
2343    By default, all options are on. Here are the available option bits:
2344    
2345    O_NL_OVERLOAD
2346           Enable overloading of REQ_NEW_LINE as described in Editing
2347           Requests. The value of this option is ignored on dynamic fields
2348           that have not reached their size limit; these have no last
2349           line, so the circumstances for triggering a REQ_NEXT_FIELD
2350           never arise.
2351           
2352    O_BS_OVERLOAD
2353           Enable overloading of REQ_DEL_PREV as described in Editing
2354           Requests.
2355           
2356    The option values are bit-masks and can be composed with logical-or in
2357    the obvious way.
2358    
2359 Custom Validation Types
2360
2361    The form library gives you the capability to define custom validation
2362    types of your own. Further, the optional additional arguments of
2363    set_field_type effectively allow you to parameterize validation types.
2364    Most of the complications in the validation-type interface have to do
2365    with the handling of the additional arguments within custom validation
2366    functions.
2367    
2368   Union Types
2369   
2370    The simplest way to create a custom data type is to compose it from
2371    two preexisting ones:
2372    
2373 FIELD *link_fieldtype(FIELDTYPE *type1,
2374                       FIELDTYPE *type2);
2375
2376    This function creates a field type that will accept any of the values
2377    legal for either of its argument field types (which may be either
2378    predefined or programmer-defined). If a set_field_type() call later
2379    requires arguments, the new composite type expects all arguments for
2380    the first type, than all arguments for the second. Order functions
2381    (see Order Requests) associated with the component types will work on
2382    the composite; what it does is check the validation function for the
2383    first type, then for the second, to figure what type the buffer
2384    contents should be treated as.
2385    
2386   New Field Types
2387   
2388    To create a field type from scratch, you need to specify one or both
2389    of the following things:
2390    
2391      * A character-validation function, to check each character as it is
2392        entered.
2393      * A field-validation function to be applied on exit from the field.
2394        
2395    Here's how you do that:
2396    
2397 typedef int     (*HOOK)();       /* pointer to function returning int */
2398
2399 FIELDTYPE *new_fieldtype(HOOK f_validate, /* field validator */
2400                          HOOK c_validate) /* character validator */
2401
2402
2403 int free_fieldtype(FIELDTYPE *ftype);     /* type to free */
2404
2405    At least one of the arguments of new_fieldtype() must be non-NULL. The
2406    forms driver will automatically call the new type's validation
2407    functions at appropriate points in processing a field of the new type.
2408    
2409    The function free_fieldtype() deallocates the argument fieldtype,
2410    freeing all storage associated with it.
2411    
2412    Normally, a field validator is called when the user attempts to leave
2413    the field. Its first argument is a field pointer, from which it can
2414    get to field buffer 0 and test it. If the function returns TRUE, the
2415    operation succeeds; if it returns FALSE, the edit cursor stays in the
2416    field.
2417    
2418    A character validator gets the character passed in as a first
2419    argument. It too should return TRUE if the character is valid, FALSE
2420    otherwise.
2421    
2422   Validation Function Arguments
2423   
2424    Your field- and character- validation functions will be passed a
2425    second argument as well. This second argument is the address of a
2426    structure (which we'll call a pile) built from any of the
2427    field-type-specific arguments passed to set_field_type(). If no such
2428    arguments are defined for the field type, this pile pointer argument
2429    will be NULL.
2430    
2431    In order to arrange for such arguments to be passed to your validation
2432    functions, you must associate a small set of storage-management
2433    functions with the type. The forms driver will use these to synthesize
2434    a pile from the trailing arguments of each set_field_type() argument,
2435    and a pointer to the pile will be passed to the validation functions.
2436    
2437    Here is how you make the association:
2438    
2439 typedef char    *(*PTRHOOK)();    /* pointer to function returning (char *) */
2440 typedef void    (*VOIDHOOK)();    /* pointer to function returning void */
2441
2442 int set_fieldtype_arg(FIELDTYPE *type,    /* type to alter */
2443                       PTRHOOK make_str,   /* make structure from args */
2444                       PTRHOOK copy_str,   /* make copy of structure */
2445                       VOIDHOOK free_str); /* free structure storage */
2446
2447    Here is how the storage-management hooks are used:
2448    
2449    make_str
2450           This function is called by set_field_type(). It gets one
2451           argument, a va_list of the type-specific arguments passed to
2452           set_field_type(). It is expected to return a pile pointer to a
2453           data structure that encapsulates those arguments.
2454           
2455    copy_str
2456           This function is called by form library functions that allocate
2457           new field instances. It is expected to take a pile pointer,
2458           copy the pile to allocated storage, and return the address of
2459           the pile copy.
2460           
2461    free_str
2462           This function is called by field- and type-deallocation
2463           routines in the library. It takes a pile pointer argument, and
2464           is expected to free the storage of that pile.
2465           
2466    The make_str and copy_str functions may return NULL to signal
2467    allocation failure. The library routines will that call them will
2468    return error indication when this happens. Thus, your validation
2469    functions should never see a NULL file pointer and need not check
2470    specially for it.
2471    
2472   Order Functions For Custom Types
2473   
2474    Some custom field types are simply ordered in the same well-defined
2475    way that TYPE_ENUM is. For such types, it is possible to define
2476    successor and predecessor functions to support the REQ_NEXT_CHOICE and
2477    REQ_PREV_CHOICE requests. Here's how:
2478    
2479 typedef int     (*INTHOOK)();     /* pointer to function returning int */
2480
2481 int set_fieldtype_arg(FIELDTYPE *type,    /* type to alter */
2482                       INTHOOK succ,       /* get successor value */
2483                       INTHOOK pred);      /* get predecessor value */
2484
2485    The successor and predecessor arguments will each be passed two
2486    arguments; a field pointer, and a pile pointer (as for the validation
2487    functions). They are expected to use the function field_buffer() to
2488    read the current value, and set_field_buffer() on buffer 0 to set the
2489    next or previous value. Either hook may return TRUE to indicate
2490    success (a legal next or previous value was set) or FALSE to indicate
2491    failure.
2492    
2493   Avoiding Problems
2494   
2495    The interface for defining custom types is complicated and tricky.
2496    Rather than attempting to create a custom type entirely from scratch,
2497    you should start by studying the library source code for whichever of
2498    the pre-defined types seems to be closest to what you want.
2499    
2500    Use that code as a model, and evolve it towards what you really want.
2501    You will avoid many problems and annoyances that way. The code in the
2502    ncurses library has been specifically exempted from the package
2503    copyright to support this.
2504    
2505    If your custom type defines order functions, have do something
2506    intuitive with a blank field. A useful convention is to make the
2507    successor of a blank field the types minimum value, and its
2508    predecessor the maximum.