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