1 Writing Programs with NCURSES
3 by Eric S. Raymond and Zeyd M. Ben-Halim
4 updates since release 1.9.9e by Thomas Dickey
9 + A Brief History of Curses
10 + Scope of This Document
13 + An Overview of Curses
14 o Compiling Programs using Curses
16 o Standard Windows and Function Naming Conventions
22 o Using Forms Characters
23 o Character Attributes and Color
26 + Function Descriptions
27 o Initialization and Wrapup
28 o Causing Output to the Terminal
29 o Low-Level Capability Access
31 + Hints, Tips, and Tricks
32 o Some Notes of Caution
33 o Temporarily Leaving ncurses Mode
34 o Using ncurses under xterm
35 o Handling Multiple Terminal Screens
36 o Testing for Terminal Capabilities
38 o Special Features of ncurses
39 + Compatibility with Older Versions
40 o Refresh of Overlapping Windows
42 + XSI Curses Conformance
44 + Compiling With the Panels Library
46 + Panels, Input, and the Standard Screen
48 + Miscellaneous Other Facilities
50 + Compiling with the menu Library
55 + Processing Menu Input
56 + Miscellaneous Other Features
58 + Compiling with the forms Library
60 + Creating and Freeing Fields and Forms
61 + Fetching and Changing Field Attributes
62 o Fetching Size and Location Data
63 o Changing the Field Location
64 o The Justification Attribute
65 o Field Display Attributes
69 + Variable-Sized Fields
77 + Direct Field Buffer Manipulation
79 + Control of Form Display
80 + Input Processing in the Forms Driver
81 o Page Navigation Requests
82 o Inter-Field Navigation Requests
83 o Intra-Field Navigation Requests
85 o Field Editing Requests
87 o Application Commands
89 + Field Change Commands
91 + Custom Validation Types
94 o Validation Function Arguments
95 o Order Functions For Custom Types
97 _________________________________________________________________
101 This document is an introduction to programming with curses. It is not
102 an exhaustive reference for the curses Application Programming
103 Interface (API); that role is filled by the curses manual pages.
104 Rather, it is intended to help C programmers ease into using the
107 This document is aimed at C applications programmers not yet
108 specifically familiar with ncurses. If you are already an experienced
109 curses programmer, you should nevertheless read the sections on Mouse
110 Interfacing, Debugging, Compatibility with Older Versions, and Hints,
111 Tips, and Tricks. These will bring you up to speed on the special
112 features and quirks of the ncurses implementation. If you are not so
113 experienced, keep reading.
115 The curses package is a subroutine library for terminal-independent
116 screen-painting and input-event handling which presents a high level
117 screen model to the programmer, hiding differences between terminal
118 types and doing automatic optimization of output to change one screen
119 full of text into another. Curses uses terminfo, which is a database
120 format that can describe the capabilities of thousands of different
123 The curses API may seem something of an archaism on UNIX desktops
124 increasingly dominated by X, Motif, and Tcl/Tk. Nevertheless, UNIX
125 still supports tty lines and X supports xterm(1); the curses API has
126 the advantage of (a) back-portability to character-cell terminals, and
127 (b) simplicity. For an application that does not require bit-mapped
128 graphics and multiple fonts, an interface implementation using curses
129 will typically be a great deal simpler and less expensive than one
132 A Brief History of Curses
134 Historically, the first ancestor of curses was the routines written to
135 provide screen-handling for the vi editor; these used the
136 already-existing termcap database facility for describing terminal
137 capabilities. These routines were abstracted into a documented library
138 and first released with the early BSD UNIX versions. All of this work
139 was done by students at the University of California.
141 After graduation, one of those students went to work at AT&T Bell
142 Labs, and made an improved termcap library called terminfo (i.e.,
143 "libterm"). That was subsequently released in System V Release 2.
144 Thereafter, other developers added to the terminfo library. For
145 instance, a student at Cornell University wrote an improved terminfo
146 library as well as a tool (tic) to compile the terminal descriptions.
147 As a general rule, AT&T did not identify the developers in the
148 source-code or documentation; the tic and infocmp programs are the
151 System V Release 3 (System III UNIX) from Bell Labs featured a
152 rewritten and much-improved curses library,l along with the tic
155 To recap, terminfo is based on Berkeley's termcap database, but
156 contains a number of improvements and extensions. Parameterized
157 capabilities strings were introduced, making it possible to describe
158 multiple video attributes, and colors and to handle far more unusual
159 terminals than possible with termcap. In the later AT&T System V
160 releases, curses evolved to use more facilities and offer more
161 capabilities, going far beyond BSD curses in power and flexibility.
163 Scope of This Document
165 This document describes ncurses, a free implementation of the System V
166 curses API with some clearly marked extensions. It includes the
167 following System V curses features:
168 * Support for multiple screen highlights (BSD curses could only
169 handle one "standout" highlight, usually reverse-video).
170 * Support for line- and box-drawing using forms characters.
171 * Recognition of function keys on input.
173 * Support for pads (windows of larger than screen size on which the
174 screen or a subwindow defines a viewport).
176 Also, this package makes use of the insert and delete line and
177 character features of terminals so equipped, and determines how to
178 optimally use these features with no help from the programmer. It
179 allows arbitrary combinations of video attributes to be displayed,
180 even on terminals that leave "magic cookies" on the screen to mark
181 changes in attributes.
183 The ncurses package can also capture and use event reports from a
184 mouse in some environments (notably, xterm under the X window system).
185 This document includes tips for using the mouse.
187 The ncurses package was originated by Pavel Curtis. The original
188 maintainer of this package is Zeyd Ben-Halim <zmbenhal@netcom.com>.
189 Eric S. Raymond <esr@snark.thyrsus.com> wrote many of the new features
190 in versions after 1.8.1 and wrote most of this introduction. Juergen
191 Pfeifer wrote all of the menu and forms code as well as the Ada95
192 binding. Ongoing work is being done by Thomas Dickey (maintainer).
193 Contact the current maintainers at bug-ncurses@gnu.org.
195 This document also describes the panels extension library, similarly
196 modeled on the SVr4 panels facility. This library allows you to
197 associate backing store with each of a stack or deck of overlapping
198 windows, and provides operations for moving windows around in the
199 stack that change their visibility in the natural way (handling window
202 Finally, this document describes in detail the menus and forms
203 extension libraries, also cloned from System V, which support easy
204 construction and sequences of menus and fill-in forms.
208 In this document, the following terminology is used with reasonable
212 A data structure describing a sub-rectangle of the screen
213 (possibly the entire screen). You can write to a window as
214 though it were a miniature screen, scrolling independently of
215 other windows on the physical screen.
218 A subset of windows which are as large as the terminal screen,
219 i.e., they start at the upper left hand corner and encompass
220 the lower right hand corner. One of these, stdscr, is
221 automatically provided for the programmer.
224 The package's idea of what the terminal display currently looks
225 like, i.e., what the user sees now. This is a special screen.
229 An Overview of Curses
231 Compiling Programs using Curses
233 In order to use the library, it is necessary to have certain types and
234 variables defined. Therefore, the programmer must have a line:
237 at the top of the program source. The screen package uses the Standard
238 I/O library, so <curses.h> includes <stdio.h>. <curses.h> also
239 includes <termios.h>, <termio.h>, or <sgtty.h> depending on your
240 system. It is redundant (but harmless) for the programmer to do these
241 includes, too. In linking with curses you need to have -lncurses in
242 your LDFLAGS or on the command line. There is no need for any other
247 In order to update the screen optimally, it is necessary for the
248 routines to know what the screen currently looks like and what the
249 programmer wants it to look like next. For this purpose, a data type
250 (structure) named WINDOW is defined which describes a window image to
251 the routines, including its starting position on the screen (the (y,
252 x) coordinates of the upper left hand corner) and its size. One of
253 these (called curscr, for current screen) is a screen image of what
254 the terminal currently looks like. Another screen (called stdscr, for
255 standard screen) is provided by default to make changes on.
257 A window is a purely internal representation. It is used to build and
258 store a potential image of a portion of the terminal. It does not bear
259 any necessary relation to what is really on the terminal screen; it is
260 more like a scratchpad or write buffer.
262 To make the section of physical screen corresponding to a window
263 reflect the contents of the window structure, the routine refresh()
264 (or wrefresh() if the window is not stdscr) is called.
266 A given physical screen section may be within the scope of any number
267 of overlapping windows. Also, changes can be made to windows in any
268 order, without regard to motion efficiency. Then, at will, the
269 programmer can effectively say "make it look like this," and let the
270 package implementation determine the most efficient way to repaint the
273 Standard Windows and Function Naming Conventions
275 As hinted above, the routines can use several windows, but two are
276 automatically given: curscr, which knows what the terminal looks like,
277 and stdscr, which is what the programmer wants the terminal to look
278 like next. The user should never actually access curscr directly.
279 Changes should be made to through the API, and then the routine
280 refresh() (or wrefresh()) called.
282 Many functions are defined to use stdscr as a default screen. For
283 example, to add a character to stdscr, one calls addch() with the
284 desired character as argument. To write to a different window. use the
285 routine waddch() (for window-specific addch()) is provided. This
286 convention of prepending function names with a "w" when they are to be
287 applied to specific windows is consistent. The only routines which do
288 not follow it are those for which a window must always be specified.
290 In order to move the current (y, x) coordinates from one point to
291 another, the routines move() and wmove() are provided. However, it is
292 often desirable to first move and then perform some I/O operation. In
293 order to avoid clumsiness, most I/O routines can be preceded by the
294 prefix "mv" and the desired (y, x) coordinates prepended to the
295 arguments to the function. For example, the calls
307 mvwaddch(win, y, x, ch);
309 Note that the window description pointer (win) comes before the added
310 (y, x) coordinates. If a function requires a window pointer, it is
311 always the first parameter passed.
315 The curses library sets some variables describing the terminal
317 type name description
318 ------------------------------------------------------------------
319 int LINES number of lines on the terminal
320 int COLS number of columns on the terminal
322 The curses.h also introduces some #define constants and types of
326 boolean type, actually a "char" (e.g., bool doneit;)
329 boolean "true" flag (1).
332 boolean "false" flag (0).
335 error flag returned by routines on a failure (-1).
338 error flag returned by routines when things go right.
342 Now we describe how to actually use the screen package. In it, we
343 assume all updating, reading, etc. is applied to stdscr. These
344 instructions will work on any window, providing you change the
345 function names and parameters as mentioned above.
347 Here is a sample program to motivate the discussion:
352 static void finish(int sig);
355 main(int argc, char *argv[])
359 /* initialize your non-curses data structures here */
361 (void) signal(SIGINT, finish); /* arrange interrupts to terminate */
363 (void) initscr(); /* initialize the curses library */
364 keypad(stdscr, TRUE); /* enable keyboard mapping */
365 (void) nonl(); /* tell curses not to do NL->CR/NL on output */
366 (void) cbreak(); /* take input chars one at a time, no wait for \n */
367 (void) echo(); /* echo input - in color */
374 * Simple color assignment, often all we need. Color pair 0 cannot
375 * be redefined. This example uses the same value for the color
376 * pair as for the foreground color, though of course that is not
379 init_pair(1, COLOR_RED, COLOR_BLACK);
380 init_pair(2, COLOR_GREEN, COLOR_BLACK);
381 init_pair(3, COLOR_YELLOW, COLOR_BLACK);
382 init_pair(4, COLOR_BLUE, COLOR_BLACK);
383 init_pair(5, COLOR_CYAN, COLOR_BLACK);
384 init_pair(6, COLOR_MAGENTA, COLOR_BLACK);
385 init_pair(7, COLOR_WHITE, COLOR_BLACK);
390 int c = getch(); /* refresh, accept single keystroke of input */
391 attrset(COLOR_PAIR(num % 8));
394 /* process the command keystroke */
397 finish(0); /* we are done */
400 static void finish(int sig)
404 /* do your non-curses wrapup here */
411 In order to use the screen package, the routines must know about
412 terminal characteristics, and the space for curscr and stdscr must be
413 allocated. These function initscr() does both these things. Since it
414 must allocate space for the windows, it can overflow memory when
415 attempting to do so. On the rare occasions this happens, initscr()
416 will terminate the program with an error message. initscr() must
417 always be called before any of the routines which affect windows are
418 used. If it is not, the program will core dump as soon as either
419 curscr or stdscr are referenced. However, it is usually best to wait
420 to call it until after you are sure you will need it, like after
421 checking for startup errors. Terminal status changing routines like
422 nl() and cbreak() should be called after initscr().
424 Once the screen windows have been allocated, you can set them up for
425 your program. If you want to, say, allow a screen to scroll, use
426 scrollok(). If you want the cursor to be left in place after the last
427 change, use leaveok(). If this is not done, refresh() will move the
428 cursor to the window's current (y, x) coordinates after updating it.
430 You can create new windows of your own using the functions newwin(),
431 derwin(), and subwin(). The routine delwin() will allow you to get rid
432 of old windows. All the options described above can be applied to any
437 Now that we have set things up, we will want to actually update the
438 terminal. The basic functions used to change what will go on a window
439 are addch() and move(). addch() adds a character at the current (y, x)
440 coordinates. move() changes the current (y, x) coordinates to whatever
441 you want them to be. It returns ERR if you try to move off the window.
442 As mentioned above, you can combine the two into mvaddch() to do both
445 The other output functions, such as addstr() and printw(), all call
446 addch() to add characters to the window.
448 After you have put on the window what you want there, when you want
449 the portion of the terminal covered by the window to be made to look
450 like it, you must call refresh(). In order to optimize finding
451 changes, refresh() assumes that any part of the window not changed
452 since the last refresh() of that window has not been changed on the
453 terminal, i.e., that you have not refreshed a portion of the terminal
454 with an overlapping window. If this is not the case, the routine
455 touchwin() is provided to make it look like the entire window has been
456 changed, thus making refresh() check the whole subsection of the
457 terminal for changes.
459 If you call wrefresh() with curscr as its argument, it will make the
460 screen look like curscr thinks it looks like. This is useful for
461 implementing a command which would redraw the screen in case it get
466 The complementary function to addch() is getch() which, if echo is
467 set, will call addch() to echo the character. Since the screen package
468 needs to know what is on the terminal at all times, if characters are
469 to be echoed, the tty must be in raw or cbreak mode. Since initially
470 the terminal has echoing enabled and is in ordinary "cooked" mode, one
471 or the other has to changed before calling getch(); otherwise, the
472 program's output will be unpredictable.
474 When you need to accept line-oriented input in a window, the functions
475 wgetstr() and friends are available. There is even a wscanw() function
476 that can do scanf()(3)-style multi-field parsing on window input.
477 These pseudo-line-oriented functions turn on echoing while they
480 The example code above uses the call keypad(stdscr, TRUE) to enable
481 support for function-key mapping. With this feature, the getch() code
482 watches the input stream for character sequences that correspond to
483 arrow and function keys. These sequences are returned as
484 pseudo-character values. The #define values returned are listed in the
485 curses.h The mapping from sequences to #define values is determined by
486 key_ capabilities in the terminal's terminfo entry.
488 Using Forms Characters
490 The addch() function (and some others, including box() and border())
491 can accept some pseudo-character arguments which are specially defined
492 by ncurses. These are #define values set up in the curses.h header;
493 see there for a complete list (look for the prefix ACS_).
495 The most useful of the ACS defines are the forms-drawing characters.
496 You can use these to draw boxes and simple graphs on the screen. If
497 the terminal does not have such characters, curses.h will map them to
498 a recognizable (though ugly) set of ASCII defaults.
500 Character Attributes and Color
502 The ncurses package supports screen highlights including standout,
503 reverse-video, underline, and blink. It also supports color, which is
504 treated as another kind of highlight.
506 Highlights are encoded, internally, as high bits of the
507 pseudo-character type (chtype) that curses.h uses to represent the
508 contents of a screen cell. See the curses.h header file for a complete
509 list of highlight mask values (look for the prefix A_).
511 There are two ways to make highlights. One is to logical-or the value
512 of the highlights you want into the character argument of an addch()
513 call, or any other output call that takes a chtype argument.
515 The other is to set the current-highlight value. This is logical-ORed
516 with any highlight you specify the first way. You do this with the
517 functions attron(), attroff(), and attrset(); see the manual pages for
518 details. Color is a special kind of highlight. The package actually
519 thinks in terms of color pairs, combinations of foreground and
520 background colors. The sample code above sets up eight color pairs,
521 all of the guaranteed-available colors on black. Note that each color
522 pair is, in effect, given the name of its foreground color. Any other
523 range of eight non-conflicting values could have been used as the
524 first arguments of the init_pair() values.
526 Once you have done an init_pair() that creates color-pair N, you can
527 use COLOR_PAIR(N) as a highlight that invokes that particular color
528 combination. Note that COLOR_PAIR(N), for constant N, is itself a
529 compile-time constant and can be used in initializers.
533 The ncurses library also provides a mouse interface.
535 NOTE: this facility is specific to ncurses, it is not part of
536 either the XSI Curses standard, nor of System V Release 4, nor BSD
537 curses. System V Release 4 curses contains code with similar
538 interface definitions, however it is not documented. Other than by
539 disassembling the library, we have no way to determine exactly how
540 that mouse code works. Thus, we recommend that you wrap
541 mouse-related code in an #ifdef using the feature macro
542 NCURSES_MOUSE_VERSION so it will not be compiled and linked on
545 Presently, mouse event reporting works in the following environments:
546 * xterm and similar programs such as rxvt.
547 * Linux console, when configured with gpm(1), Alessandro Rubini's
549 * FreeBSD sysmouse (console)
552 The mouse interface is very simple. To activate it, you use the
553 function mousemask(), passing it as first argument a bit-mask that
554 specifies what kinds of events you want your program to be able to
555 see. It will return the bit-mask of events that actually become
556 visible, which may differ from the argument if the mouse device is not
557 capable of reporting some of the event types you specify.
559 Once the mouse is active, your application's command loop should watch
560 for a return value of KEY_MOUSE from wgetch(). When you see this, a
561 mouse event report has been queued. To pick it off the queue, use the
562 function getmouse() (you must do this before the next wgetch(),
563 otherwise another mouse event might come in and make the first one
566 Each call to getmouse() fills a structure (the address of which you
567 will pass it) with mouse event data. The event data includes
568 zero-origin, screen-relative character-cell coordinates of the mouse
569 pointer. It also includes an event mask. Bits in this mask will be
570 set, corresponding to the event type being reported.
572 The mouse structure contains two additional fields which may be
573 significant in the future as ncurses interfaces to new kinds of
574 pointing device. In addition to x and y coordinates, there is a slot
575 for a z coordinate; this might be useful with touch-screens that can
576 return a pressure or duration parameter. There is also a device ID
577 field, which could be used to distinguish between multiple pointing
580 The class of visible events may be changed at any time via
581 mousemask(). Events that can be reported include presses, releases,
582 single-, double- and triple-clicks (you can set the maximum
583 button-down time for clicks). If you do not make clicks visible, they
584 will be reported as press-release pairs. In some environments, the
585 event mask may include bits reporting the state of shift, alt, and
586 ctrl keys on the keyboard during the event.
588 A function to check whether a mouse event fell within a given window
589 is also supplied. You can use this to see whether a given window
590 should consider a mouse event relevant to it.
592 Because mouse event reporting will not be available in all
593 environments, it would be unwise to build ncurses applications that
594 require the use of a mouse. Rather, you should use the mouse as a
595 shortcut for point-and-shoot commands your application would normally
596 accept from the keyboard. Two of the test games in the ncurses
597 distribution (bs and knight) contain code that illustrates how this
600 See the manual page curs_mouse(3X) for full details of the
601 mouse-interface functions.
605 In order to clean up after the ncurses routines, the routine endwin()
606 is provided. It restores tty modes to what they were when initscr()
607 was first called, and moves the cursor down to the lower-left corner.
608 Thus, anytime after the call to initscr, endwin() should be called
611 Function Descriptions
613 We describe the detailed behavior of some important curses functions
614 here, as a supplement to the manual page descriptions.
616 Initialization and Wrapup
619 The first function called should almost always be initscr().
620 This will determine the terminal type and initialize curses
621 data structures. initscr() also arranges that the first call to
622 refresh() will clear the screen. If an error occurs a message
623 is written to standard error and the program exits. Otherwise
624 it returns a pointer to stdscr. A few functions may be called
625 before initscr (slk_init(), filter(), ripoffline(), use_env(),
626 and, if you are using multiple terminals, newterm().)
629 Your program should always call endwin() before exiting or
630 shelling out of the program. This function will restore tty
631 modes, move the cursor to the lower left corner of the screen,
632 reset the terminal into the proper non-visual mode. Calling
633 refresh() or doupdate() after a temporary escape from the
634 program will restore the ncurses screen from before the escape.
636 newterm(type, ofp, ifp)
637 A program which outputs to more than one terminal should use
638 newterm() instead of initscr(). newterm() should be called once
639 for each terminal. It returns a variable of type SCREEN * which
640 should be saved as a reference to that terminal. (NOTE: a
641 SCREEN variable is not a screen in the sense we are describing
642 in this introduction, but a collection of parameters used to
643 assist in optimizing the display.) The arguments are the type
644 of the terminal (a string) and FILE pointers for the output and
645 input of the terminal. If type is NULL then the environment
646 variable $TERM is used. endwin() should called once at wrapup
647 time for each terminal opened using this function.
650 This function is used to switch to a different terminal
651 previously opened by newterm(). The screen reference for the
652 new terminal is passed as the parameter. The previous terminal
653 is returned by the function. All other calls affect only the
657 The inverse of newterm(); deallocates the data structures
658 associated with a given SCREEN reference.
660 Causing Output to the Terminal
662 refresh() and wrefresh(win)
663 These functions must be called to actually get any output on
664 the terminal, as other routines merely manipulate data
665 structures. wrefresh() copies the named window to the physical
666 terminal screen, taking into account what is already there in
667 order to do optimizations. refresh() does a refresh of stdscr.
668 Unless leaveok() has been enabled, the physical cursor of the
669 terminal is left at the location of the window's cursor.
671 doupdate() and wnoutrefresh(win)
672 These two functions allow multiple updates with more efficiency
673 than wrefresh. To use them, it is important to understand how
674 curses works. In addition to all the window structures, curses
675 keeps two data structures representing the terminal screen: a
676 physical screen, describing what is actually on the screen, and
677 a virtual screen, describing what the programmer wants to have
678 on the screen. wrefresh works by first copying the named window
679 to the virtual screen (wnoutrefresh()), and then calling the
680 routine to update the screen (doupdate()). If the programmer
681 wishes to output several windows at once, a series of calls to
682 wrefresh will result in alternating calls to wnoutrefresh() and
683 doupdate(), causing several bursts of output to the screen. By
684 calling wnoutrefresh() for each window, it is then possible to
685 call doupdate() once, resulting in only one burst of output,
686 with fewer total characters transmitted (this also avoids a
687 visually annoying flicker at each update).
689 Low-Level Capability Access
691 setupterm(term, filenum, errret)
692 This routine is called to initialize a terminal's description,
693 without setting up the curses screen structures or changing the
694 tty-driver mode bits. term is the character string representing
695 the name of the terminal being used. filenum is the UNIX file
696 descriptor of the terminal to be used for output. errret is a
697 pointer to an integer, in which a success or failure indication
698 is returned. The values returned can be 1 (all is well), 0 (no
699 such terminal), or -1 (some problem locating the terminfo
702 The value of term can be given as NULL, which will cause the
703 value of TERM in the environment to be used. The errret pointer
704 can also be given as NULL, meaning no error code is wanted. If
705 errret is defaulted, and something goes wrong, setupterm() will
706 print an appropriate error message and exit, rather than
707 returning. Thus, a simple program can call setupterm(0, 1, 0)
708 and not worry about initialization errors.
710 After the call to setupterm(), the global variable cur_term is
711 set to point to the current structure of terminal capabilities.
712 By calling setupterm() for each terminal, and saving and
713 restoring cur_term, it is possible for a program to use two or
714 more terminals at once. Setupterm() also stores the names
715 section of the terminal description in the global character
716 array ttytype[]. Subsequent calls to setupterm() will overwrite
717 this array, so you will have to save it yourself if need be.
721 NOTE: These functions are not part of the standard curses API!
724 This function can be used to explicitly set a trace level. If
725 the trace level is nonzero, execution of your program will
726 generate a file called "trace" in the current working directory
727 containing a report on the library's actions. Higher trace
728 levels enable more detailed (and verbose) reporting -- see
729 comments attached to TRACE_ defines in the curses.h file for
730 details. (It is also possible to set a trace level by assigning
731 a trace level value to the environment variable NCURSES_TRACE).
734 This function can be used to output your own debugging
735 information. It is only available only if you link with
736 -lncurses_g. It can be used the same way as printf(), only it
737 outputs a newline after the end of arguments. The output goes
738 to a file called trace in the current directory.
740 Trace logs can be difficult to interpret due to the sheer volume of
741 data dumped in them. There is a script called tracemunch included with
742 the ncurses distribution that can alleviate this problem somewhat; it
743 compacts long sequences of similar operations into more succinct
744 single-line pseudo-operations. These pseudo-ops can be distinguished
745 by the fact that they are named in capital letters.
747 Hints, Tips, and Tricks
749 The ncurses manual pages are a complete reference for this library. In
750 the remainder of this document, we discuss various useful methods that
751 may not be obvious from the manual page descriptions.
753 Some Notes of Caution
755 If you find yourself thinking you need to use noraw() or nocbreak(),
756 think again and move carefully. It is probably better design to use
757 getstr() or one of its relatives to simulate cooked mode. The noraw()
758 and nocbreak() functions try to restore cooked mode, but they may end
759 up clobbering some control bits set before you started your
760 application. Also, they have always been poorly documented, and are
761 likely to hurt your application's usability with other curses
764 Bear in mind that refresh() is a synonym for wrefresh(stdscr). Do not
765 try to mix use of stdscr with use of windows declared by newwin(); a
766 refresh() call will blow them off the screen. The right way to handle
767 this is to use subwin(), or not touch stdscr at all and tile your
768 screen with declared windows which you then wnoutrefresh() somewhere
769 in your program event loop, with a single doupdate() call to trigger
772 You are much less likely to run into problems if you design your
773 screen layouts to use tiled rather than overlapping windows.
774 Historically, curses support for overlapping windows has been weak,
775 fragile, and poorly documented. The ncurses library is not yet an
776 exception to this rule.
778 There is a panels library included in the ncurses distribution that
779 does a pretty good job of strengthening the overlapping-windows
782 Try to avoid using the global variables LINES and COLS. Use getmaxyx()
783 on the stdscr context instead. Reason: your code may be ported to run
784 in an environment with window resizes, in which case several screens
785 could be open with different sizes.
787 Temporarily Leaving NCURSES Mode
789 Sometimes you will want to write a program that spends most of its
790 time in screen mode, but occasionally returns to ordinary "cooked"
791 mode. A common reason for this is to support shell-out. This behavior
792 is simple to arrange in ncurses.
794 To leave ncurses mode, call endwin() as you would if you were
795 intending to terminate the program. This will take the screen back to
796 cooked mode; you can do your shell-out. When you want to return to
797 ncurses mode, simply call refresh() or doupdate(). This will repaint
800 There is a boolean function, isendwin(), which code can use to test
801 whether ncurses screen mode is active. It returns TRUE in the interval
802 between an endwin() call and the following refresh(), FALSE otherwise.
804 Here is some sample code for shellout:
805 addstr("Shelling out...");
806 def_prog_mode(); /* save current tty modes */
807 endwin(); /* restore original tty modes */
808 system("sh"); /* run shell */
809 addstr("returned.\n"); /* prepare return message */
810 refresh(); /* restore save modes, repaint screen */
812 Using NCURSES under XTERM
814 A resize operation in X sends SIGWINCH to the application running
815 under xterm. The easiest way to handle SIGWINCH is to do an endwin,
816 followed by an refresh and a screen repaint you code yourself. The
817 refresh will pick up the new screen size from the xterm's environment.
819 That is the standard way, of course (it even works with some vendor's
820 curses implementations). Its drawback is that it clears the screen to
821 reinitialize the display, and does not resize subwindows which must be
822 shrunk. Ncurses provides an extension which works better, the
823 resizeterm function. That function ensures that all windows are
824 limited to the new screen dimensions, and pads stdscr with blanks if
825 the screen is larger.
827 The ncurses library provides a SIGWINCH signal handler, which pushes a
828 KEY_RESIZE via the wgetch() calls. When ncurses returns that code, it
829 calls resizeterm to update the size of the standard screen's window,
830 repainting that (filling with blanks or truncating as needed). It also
831 resizes other windows, but its effect may be less satisfactory because
832 it cannot know how you want the screen re-painted. You will usually
833 have to write special-purpose code to handle KEY_RESIZE yourself.
835 Handling Multiple Terminal Screens
837 The initscr() function actually calls a function named newterm() to do
838 most of its work. If you are writing a program that opens multiple
839 terminals, use newterm() directly.
841 For each call, you will have to specify a terminal type and a pair of
842 file pointers; each call will return a screen reference, and stdscr
843 will be set to the last one allocated. You will switch between screens
844 with the set_term call. Note that you will also have to call
845 def_shell_mode and def_prog_mode on each tty yourself.
847 Testing for Terminal Capabilities
849 Sometimes you may want to write programs that test for the presence of
850 various capabilities before deciding whether to go into ncurses mode.
851 An easy way to do this is to call setupterm(), then use the functions
852 tigetflag(), tigetnum(), and tigetstr() to do your testing.
854 A particularly useful case of this often comes up when you want to
855 test whether a given terminal type should be treated as "smart"
856 (cursor-addressable) or "stupid". The right way to test this is to see
857 if the return value of tigetstr("cup") is non-NULL. Alternatively, you
858 can include the term.h file and test the value of the macro
863 Use the addchstr() family of functions for fast screen-painting of
864 text when you know the text does not contain any control characters.
865 Try to make attribute changes infrequent on your screens. Do not use
866 the immedok() option!
868 Special Features of NCURSES
870 The wresize() function allows you to resize a window in place. The
871 associated resizeterm() function simplifies the construction of
872 SIGWINCH handlers, for resizing all windows.
874 The define_key() function allows you to define at runtime function-key
875 control sequences which are not in the terminal description. The
876 keyok() function allows you to temporarily enable or disable
877 interpretation of any function-key control sequence.
879 The use_default_colors() function allows you to construct applications
880 which can use the terminal's default foreground and background colors
881 as an additional "default" color. Several terminal emulators support
882 this feature, which is based on ISO 6429.
884 Ncurses supports up 16 colors, unlike SVr4 curses which defines only
885 8. While most terminals which provide color allow only 8 colors, about
886 a quarter (including XFree86 xterm) support 16 colors.
888 Compatibility with Older Versions
890 Despite our best efforts, there are some differences between ncurses
891 and the (undocumented!) behavior of older curses implementations.
892 These arise from ambiguities or omissions in the documentation of the
895 Refresh of Overlapping Windows
897 If you define two windows A and B that overlap, and then alternately
898 scribble on and refresh them, the changes made to the overlapping
899 region under historic curses versions were often not documented
902 To understand why this is a problem, remember that screen updates are
903 calculated between two representations of the entire display. The
904 documentation says that when you refresh a window, it is first copied
905 to the virtual screen, and then changes are calculated to update the
906 physical screen (and applied to the terminal). But "copied to" is not
907 very specific, and subtle differences in how copying works can produce
908 different behaviors in the case where two overlapping windows are each
909 being refreshed at unpredictable intervals.
911 What happens to the overlapping region depends on what wnoutrefresh()
912 does with its argument -- what portions of the argument window it
913 copies to the virtual screen. Some implementations do "change copy",
914 copying down only locations in the window that have changed (or been
915 marked changed with wtouchln() and friends). Some implementations do
916 "entire copy", copying all window locations to the virtual screen
917 whether or not they have changed.
919 The ncurses library itself has not always been consistent on this
920 score. Due to a bug, versions 1.8.7 to 1.9.8a did entire copy.
921 Versions 1.8.6 and older, and versions 1.9.9 and newer, do change
924 For most commercial curses implementations, it is not documented and
925 not known for sure (at least not to the ncurses maintainers) whether
926 they do change copy or entire copy. We know that System V release 3
927 curses has logic in it that looks like an attempt to do change copy,
928 but the surrounding logic and data representations are sufficiently
929 complex, and our knowledge sufficiently indirect, that it is hard to
930 know whether this is reliable. It is not clear what the SVr4
931 documentation and XSI standard intend. The XSI Curses standard barely
932 mentions wnoutrefresh(); the SVr4 documents seem to be describing
933 entire-copy, but it is possible with some effort and straining to read
936 It might therefore be unwise to rely on either behavior in programs
937 that might have to be linked with other curses implementations.
938 Instead, you can do an explicit touchwin() before the wnoutrefresh()
939 call to guarantee an entire-contents copy anywhere.
941 The really clean way to handle this is to use the panels library. If,
942 when you want a screen update, you do update_panels(), it will do all
943 the necessary wnoutrefresh() calls for whatever panel stacking order
944 you have defined. Then you can do one doupdate() and there will be a
945 single burst of physical I/O that will do all your updates.
949 If you have been using a very old versions of ncurses (1.8.7 or older)
950 you may be surprised by the behavior of the erase functions. In older
951 versions, erased areas of a window were filled with a blank modified
952 by the window's current attribute (as set by wattrset(), wattron(),
953 wattroff() and friends).
955 In newer versions, this is not so. Instead, the attribute of erased
956 blanks is normal unless and until it is modified by the functions
957 bkgdset() or wbkgdset().
959 This change in behavior conforms ncurses to System V Release 4 and the
962 XSI Curses Conformance
964 The ncurses library is intended to be base-level conformant with the
965 XSI Curses standard from X/Open. Many extended-level features (in
966 fact, almost all features not directly concerned with wide characters
967 and internationalization) are also supported.
969 One effect of XSI conformance is the change in behavior described
970 under "Background Erase -- Compatibility with Old Versions".
972 Also, ncurses meets the XSI requirement that every macro entry point
973 have a corresponding function which may be linked (and will be
974 prototype-checked) if the macro definition is disabled with #undef.
978 The ncurses library by itself provides good support for screen
979 displays in which the windows are tiled (non-overlapping). In the more
980 general case that windows may overlap, you have to use a series of
981 wnoutrefresh() calls followed by a doupdate(), and be careful about
982 the order you do the window refreshes in. It has to be bottom-upwards,
983 otherwise parts of windows that should be obscured will show through.
985 When your interface design is such that windows may dive deeper into
986 the visibility stack or pop to the top at runtime, the resulting
987 book-keeping can be tedious and difficult to get right. Hence the
990 The panel library first appeared in AT&T System V. The version
991 documented here is the panel code distributed with ncurses.
993 Compiling With the Panels Library
995 Your panels-using modules must import the panels library declarations
999 and must be linked explicitly with the panels library using an -lpanel
1000 argument. Note that they must also link the ncurses library with
1001 -lncurses. Many linkers are two-pass and will accept either order, but
1002 it is still good practice to put -lpanel first and -lncurses second.
1006 A panel object is a window that is implicitly treated as part of a
1007 deck including all other panel objects. The deck has an implicit
1008 bottom-to-top visibility order. The panels library includes an update
1009 function (analogous to refresh()) that displays all panels in the deck
1010 in the proper order to resolve overlaps. The standard window, stdscr,
1011 is considered below all panels.
1013 Details on the panels functions are available in the man pages. We
1014 will just hit the highlights here.
1016 You create a panel from a window by calling new_panel() on a window
1017 pointer. It then becomes the top of the deck. The panel's window is
1018 available as the value of panel_window() called with the panel pointer
1021 You can delete a panel (removing it from the deck) with del_panel.
1022 This will not deallocate the associated window; you have to do that
1023 yourself. You can replace a panel's window with a different window by
1024 calling replace_window. The new window may be of different size; the
1025 panel code will re-compute all overlaps. This operation does not
1026 change the panel's position in the deck.
1028 To move a panel's window, use move_panel(). The mvwin() function on
1029 the panel's window is not sufficient because it does not update the
1030 panels library's representation of where the windows are. This
1031 operation leaves the panel's depth, contents, and size unchanged.
1033 Two functions (top_panel(), bottom_panel()) are provided for
1034 rearranging the deck. The first pops its argument window to the top of
1035 the deck; the second sends it to the bottom. Either operation leaves
1036 the panel's screen location, contents, and size unchanged.
1038 The function update_panels() does all the wnoutrefresh() calls needed
1039 to prepare for doupdate() (which you must call yourself, afterwards).
1041 Typically, you will want to call update_panels() and doupdate() just
1042 before accepting command input, once in each cycle of interaction with
1043 the user. If you call update_panels() after each and every panel
1044 write, you will generate a lot of unnecessary refresh activity and
1047 Panels, Input, and the Standard Screen
1049 You should not mix wnoutrefresh() or wrefresh() operations with panels
1050 code; this will work only if the argument window is either in the top
1051 panel or unobscured by any other panels.
1053 The stsdcr window is a special case. It is considered below all
1054 panels. Because changes to panels may obscure parts of stdscr, though,
1055 you should call update_panels() before doupdate() even when you only
1058 Note that wgetch automatically calls wrefresh. Therefore, before
1059 requesting input from a panel window, you need to be sure that the
1060 panel is totally unobscured.
1062 There is presently no way to display changes to one obscured panel
1063 without repainting all panels.
1067 It is possible to remove a panel from the deck temporarily; use
1068 hide_panel for this. Use show_panel() to render it visible again. The
1069 predicate function panel_hidden tests whether or not a panel is
1072 The panel_update code ignores hidden panels. You cannot do top_panel()
1073 or bottom_panel on a hidden panel(). Other panels operations are
1076 Miscellaneous Other Facilities
1078 It is possible to navigate the deck using the functions panel_above()
1079 and panel_below. Handed a panel pointer, they return the panel above
1080 or below that panel. Handed NULL, they return the bottom-most or
1083 Every panel has an associated user pointer, not used by the panel
1084 code, to which you can attach application data. See the man page
1085 documentation of set_panel_userptr() and panel_userptr for details.
1089 A menu is a screen display that assists the user to choose some subset
1090 of a given set of items. The menu library is a curses extension that
1091 supports easy programming of menu hierarchies with a uniform but
1094 The menu library first appeared in AT&T System V. The version
1095 documented here is the menu code distributed with ncurses.
1097 Compiling With the menu Library
1099 Your menu-using modules must import the menu library declarations with
1102 and must be linked explicitly with the menus library using an -lmenu
1103 argument. Note that they must also link the ncurses library with
1104 -lncurses. Many linkers are two-pass and will accept either order, but
1105 it is still good practice to put -lmenu first and -lncurses second.
1109 The menus created by this library consist of collections of items
1110 including a name string part and a description string part. To make
1111 menus, you create groups of these items and connect them with menu
1114 The menu can then by posted, that is written to an associated window.
1115 Actually, each menu has two associated windows; a containing window in
1116 which the programmer can scribble titles or borders, and a subwindow
1117 in which the menu items proper are displayed. If this subwindow is too
1118 small to display all the items, it will be a scrollable viewport on
1119 the collection of items.
1121 A menu may also be unposted (that is, undisplayed), and finally freed
1122 to make the storage associated with it and its items available for
1125 The general flow of control of a menu program looks like this:
1126 1. Initialize curses.
1127 2. Create the menu items, using new_item().
1128 3. Create the menu using new_menu().
1129 4. Post the menu using post_menu().
1130 5. Refresh the screen.
1131 6. Process user requests via an input loop.
1132 7. Unpost the menu using unpost_menu().
1133 8. Free the menu, using free_menu().
1134 9. Free the items using free_item().
1135 10. Terminate curses.
1139 Menus may be multi-valued or (the default) single-valued (see the
1140 manual page menu_opts(3x) to see how to change the default). Both
1141 types always have a current item.
1143 From a single-valued menu you can read the selected value simply by
1144 looking at the current item. From a multi-valued menu, you get the
1145 selected set by looping through the items applying the item_value()
1146 predicate function. Your menu-processing code can use the function
1147 set_item_value() to flag the items in the select set.
1149 Menu items can be made unselectable using set_item_opts() or
1150 item_opts_off() with the O_SELECTABLE argument. This is the only
1151 option so far defined for menus, but it is good practice to code as
1152 though other option bits might be on.
1156 The menu library calculates a minimum display size for your window,
1157 based on the following variables:
1158 * The number and maximum length of the menu items
1159 * Whether the O_ROWMAJOR option is enabled
1160 * Whether display of descriptions is enabled
1161 * Whatever menu format may have been set by the programmer
1162 * The length of the menu mark string used for highlighting selected
1165 The function set_menu_format() allows you to set the maximum size of
1166 the viewport or menu page that will be used to display menu items. You
1167 can retrieve any format associated with a menu with menu_format(). The
1168 default format is rows=16, columns=1.
1170 The actual menu page may be smaller than the format size. This depends
1171 on the item number and size and whether O_ROWMAJOR is on. This option
1172 (on by default) causes menu items to be displayed in a "raster-scan"
1173 pattern, so that if more than one item will fit horizontally the first
1174 couple of items are side-by-side in the top row. The alternative is
1175 column-major display, which tries to put the first several items in
1178 As mentioned above, a menu format not large enough to allow all items
1179 to fit on-screen will result in a menu display that is vertically
1182 You can scroll it with requests to the menu driver, which will be
1183 described in the section on menu input handling.
1185 Each menu has a mark string used to visually tag selected items; see
1186 the menu_mark(3x) manual page for details. The mark string length also
1187 influences the menu page size.
1189 The function scale_menu() returns the minimum display size that the
1190 menu code computes from all these factors. There are other menu
1191 display attributes including a select attribute, an attribute for
1192 selectable items, an attribute for unselectable items, and a pad
1193 character used to separate item name text from description text. These
1194 have reasonable defaults which the library allows you to change (see
1195 the menu_attribs(3x) manual page.
1199 Each menu has, as mentioned previously, a pair of associated windows.
1200 Both these windows are painted when the menu is posted and erased when
1201 the menu is unposted.
1203 The outer or frame window is not otherwise touched by the menu
1204 routines. It exists so the programmer can associate a title, a border,
1205 or perhaps help text with the menu and have it properly refreshed or
1206 erased at post/unpost time. The inner window or subwindow is where the
1207 current menu page is displayed.
1209 By default, both windows are stdscr. You can set them with the
1210 functions in menu_win(3x).
1212 When you call post_menu(), you write the menu to its subwindow. When
1213 you call unpost_menu(), you erase the subwindow, However, neither of
1214 these actually modifies the screen. To do that, call wrefresh() or
1217 Processing Menu Input
1219 The main loop of your menu-processing code should call menu_driver()
1220 repeatedly. The first argument of this routine is a menu pointer; the
1221 second is a menu command code. You should write an input-fetching
1222 routine that maps input characters to menu command codes, and pass its
1223 output to menu_driver(). The menu command codes are fully documented
1226 The simplest group of command codes is REQ_NEXT_ITEM, REQ_PREV_ITEM,
1227 REQ_FIRST_ITEM, REQ_LAST_ITEM, REQ_UP_ITEM, REQ_DOWN_ITEM,
1228 REQ_LEFT_ITEM, REQ_RIGHT_ITEM. These change the currently selected
1229 item. These requests may cause scrolling of the menu page if it only
1230 partially displayed.
1232 There are explicit requests for scrolling which also change the
1233 current item (because the select location does not change, but the
1234 item there does). These are REQ_SCR_DLINE, REQ_SCR_ULINE,
1235 REQ_SCR_DPAGE, and REQ_SCR_UPAGE.
1237 The REQ_TOGGLE_ITEM selects or deselects the current item. It is for
1238 use in multi-valued menus; if you use it with O_ONEVALUE on, you will
1239 get an error return (E_REQUEST_DENIED).
1241 Each menu has an associated pattern buffer. The menu_driver() logic
1242 tries to accumulate printable ASCII characters passed in in that
1243 buffer; when it matches a prefix of an item name, that item (or the
1244 next matching item) is selected. If appending a character yields no
1245 new match, that character is deleted from the pattern buffer, and
1246 menu_driver() returns E_NO_MATCH.
1248 Some requests change the pattern buffer directly: REQ_CLEAR_PATTERN,
1249 REQ_BACK_PATTERN, REQ_NEXT_MATCH, REQ_PREV_MATCH. The latter two are
1250 useful when pattern buffer input matches more than one item in a
1253 Each successful scroll or item navigation request clears the pattern
1254 buffer. It is also possible to set the pattern buffer explicitly with
1257 Finally, menu driver requests above the constant MAX_COMMAND are
1258 considered application-specific commands. The menu_driver() code
1259 ignores them and returns E_UNKNOWN_COMMAND.
1261 Miscellaneous Other Features
1263 Various menu options can affect the processing and visual appearance
1264 and input processing of menus. See menu_opts(3x) for details.
1266 It is possible to change the current item from application code; this
1267 is useful if you want to write your own navigation requests. It is
1268 also possible to explicitly set the top row of the menu display. See
1269 mitem_current(3x). If your application needs to change the menu
1270 subwindow cursor for any reason, pos_menu_cursor() will restore it to
1271 the correct location for continuing menu driver processing.
1273 It is possible to set hooks to be called at menu initialization and
1274 wrapup time, and whenever the selected item changes. See
1277 Each item, and each menu, has an associated user pointer on which you
1278 can hang application data. See mitem_userptr(3x) and menu_userptr(3x).
1282 The form library is a curses extension that supports easy programming
1283 of on-screen forms for data entry and program control.
1285 The form library first appeared in AT&T System V. The version
1286 documented here is the form code distributed with ncurses.
1288 Compiling With the form Library
1290 Your form-using modules must import the form library declarations with
1293 and must be linked explicitly with the forms library using an -lform
1294 argument. Note that they must also link the ncurses library with
1295 -lncurses. Many linkers are two-pass and will accept either order, but
1296 it is still good practice to put -lform first and -lncurses second.
1300 A form is a collection of fields; each field may be either a label
1301 (explanatory text) or a data-entry location. Long forms may be
1302 segmented into pages; each entry to a new page clears the screen.
1304 To make forms, you create groups of fields and connect them with form
1305 frame objects; the form library makes this relatively simple.
1307 Once defined, a form can be posted, that is written to an associated
1308 window. Actually, each form has two associated windows; a containing
1309 window in which the programmer can scribble titles or borders, and a
1310 subwindow in which the form fields proper are displayed.
1312 As the form user fills out the posted form, navigation and editing
1313 keys support movement between fields, editing keys support modifying
1314 field, and plain text adds to or changes data in a current field. The
1315 form library allows you (the forms designer) to bind each navigation
1316 and editing key to any keystroke accepted by curses Fields may have
1317 validation conditions on them, so that they check input data for type
1318 and value. The form library supplies a rich set of pre-defined field
1319 types, and makes it relatively easy to define new ones.
1321 Once its transaction is completed (or aborted), a form may be unposted
1322 (that is, undisplayed), and finally freed to make the storage
1323 associated with it and its items available for re-use.
1325 The general flow of control of a form program looks like this:
1326 1. Initialize curses.
1327 2. Create the form fields, using new_field().
1328 3. Create the form using new_form().
1329 4. Post the form using post_form().
1330 5. Refresh the screen.
1331 6. Process user requests via an input loop.
1332 7. Unpost the form using unpost_form().
1333 8. Free the form, using free_form().
1334 9. Free the fields using free_field().
1335 10. Terminate curses.
1337 Note that this looks much like a menu program; the form library
1338 handles tasks which are in many ways similar, and its interface was
1339 obviously designed to resemble that of the menu library wherever
1342 In forms programs, however, the "process user requests" is somewhat
1343 more complicated than for menus. Besides menu-like navigation
1344 operations, the menu driver loop has to support field editing and data
1347 Creating and Freeing Fields and Forms
1349 The basic function for creating fields is new_field():
1350 FIELD *new_field(int height, int width, /* new field size */
1351 int top, int left, /* upper left corner */
1352 int offscreen, /* number of offscreen rows */
1353 int nbuf); /* number of working buffers */
1355 Menu items always occupy a single row, but forms fields may have
1356 multiple rows. So new_field() requires you to specify a width and
1357 height (the first two arguments, which mist both be greater than
1360 You must also specify the location of the field's upper left corner on
1361 the screen (the third and fourth arguments, which must be zero or
1362 greater). Note that these coordinates are relative to the form
1363 subwindow, which will coincide with stdscr by default but need not be
1364 stdscr if you have done an explicit set_form_win() call.
1366 The fifth argument allows you to specify a number of off-screen rows.
1367 If this is zero, the entire field will always be displayed. If it is
1368 nonzero, the form will be scrollable, with only one screen-full
1369 (initially the top part) displayed at any given time. If you make a
1370 field dynamic and grow it so it will no longer fit on the screen, the
1371 form will become scrollable even if the offscreen argument was
1374 The forms library allocates one working buffer per field; the size of
1375 each buffer is ((height + offscreen)*width + 1, one character for each
1376 position in the field plus a NUL terminator. The sixth argument is the
1377 number of additional data buffers to allocate for the field; your
1378 application can use them for its own purposes.
1379 FIELD *dup_field(FIELD *field, /* field to copy */
1380 int top, int left); /* location of new copy */
1382 The function dup_field() duplicates an existing field at a new
1383 location. Size and buffering information are copied; some attribute
1384 flags and status bits are not (see the form_field_new(3X) for
1386 FIELD *link_field(FIELD *field, /* field to copy */
1387 int top, int left); /* location of new copy */
1389 The function link_field() also duplicates an existing field at a new
1390 location. The difference from dup_field() is that it arranges for the
1391 new field's buffer to be shared with the old one.
1393 Besides the obvious use in making a field editable from two different
1394 form pages, linked fields give you a way to hack in dynamic labels. If
1395 you declare several fields linked to an original, and then make them
1396 inactive, changes from the original will still be propagated to the
1399 As with duplicated fields, linked fields have attribute bits separate
1402 As you might guess, all these field-allocations return NULL if the
1403 field allocation is not possible due to an out-of-memory error or
1404 out-of-bounds arguments.
1406 To connect fields to a form, use
1407 FORM *new_form(FIELD **fields);
1409 This function expects to see a NULL-terminated array of field
1410 pointers. Said fields are connected to a newly-allocated form object;
1411 its address is returned (or else NULL if the allocation fails).
1413 Note that new_field() does not copy the pointer array into private
1414 storage; if you modify the contents of the pointer array during forms
1415 processing, all manner of bizarre things might happen. Also note that
1416 any given field may only be connected to one form.
1418 The functions free_field() and free_form are available to free field
1419 and form objects. It is an error to attempt to free a field connected
1420 to a form, but not vice-versa; thus, you will generally free your form
1423 Fetching and Changing Field Attributes
1425 Each form field has a number of location and size attributes
1426 associated with it. There are other field attributes used to control
1427 display and editing of the field. Some (for example, the O_STATIC bit)
1428 involve sufficient complications to be covered in sections of their
1429 own later on. We cover the functions used to get and set several basic
1432 When a field is created, the attributes not specified by the new_field
1433 function are copied from an invisible system default field. In
1434 attribute-setting and -fetching functions, the argument NULL is taken
1435 to mean this field. Changes to it persist as defaults until your forms
1436 application terminates.
1438 Fetching Size and Location Data
1440 You can retrieve field sizes and locations through:
1441 int field_info(FIELD *field, /* field from which to fetch */
1442 int *height, *int width, /* field size */
1443 int *top, int *left, /* upper left corner */
1444 int *offscreen, /* number of offscreen rows */
1445 int *nbuf); /* number of working buffers */
1447 This function is a sort of inverse of new_field(); instead of setting
1448 size and location attributes of a new field, it fetches them from an
1451 Changing the Field Location
1453 It is possible to move a field's location on the screen:
1454 int move_field(FIELD *field, /* field to alter */
1455 int top, int left); /* new upper-left corner */
1457 You can, of course. query the current location through field_info().
1459 The Justification Attribute
1461 One-line fields may be unjustified, justified right, justified left,
1462 or centered. Here is how you manipulate this attribute:
1463 int set_field_just(FIELD *field, /* field to alter */
1464 int justmode); /* mode to set */
1466 int field_just(FIELD *field); /* fetch mode of field */
1468 The mode values accepted and returned by this functions are
1469 preprocessor macros NO_JUSTIFICATION, JUSTIFY_RIGHT, JUSTIFY_LEFT, or
1472 Field Display Attributes
1474 For each field, you can set a foreground attribute for entered
1475 characters, a background attribute for the entire field, and a pad
1476 character for the unfilled portion of the field. You can also control
1477 pagination of the form.
1479 This group of four field attributes controls the visual appearance of
1480 the field on the screen, without affecting in any way the data in the
1482 int set_field_fore(FIELD *field, /* field to alter */
1483 chtype attr); /* attribute to set */
1485 chtype field_fore(FIELD *field); /* field to query */
1487 int set_field_back(FIELD *field, /* field to alter */
1488 chtype attr); /* attribute to set */
1490 chtype field_back(FIELD *field); /* field to query */
1492 int set_field_pad(FIELD *field, /* field to alter */
1493 int pad); /* pad character to set */
1495 chtype field_pad(FIELD *field);
1497 int set_new_page(FIELD *field, /* field to alter */
1498 int flag); /* TRUE to force new page */
1500 chtype new_page(FIELD *field); /* field to query */
1502 The attributes set and returned by the first four functions are normal
1503 curses(3x) display attribute values (A_STANDOUT, A_BOLD, A_REVERSE
1504 etc). The page bit of a field controls whether it is displayed at the
1505 start of a new form screen.
1509 There is also a large collection of field option bits you can set to
1510 control various aspects of forms processing. You can manipulate them
1511 with these functions:
1512 int set_field_opts(FIELD *field, /* field to alter */
1513 int attr); /* attribute to set */
1515 int field_opts_on(FIELD *field, /* field to alter */
1516 int attr); /* attributes to turn on */
1518 int field_opts_off(FIELD *field, /* field to alter */
1519 int attr); /* attributes to turn off */
1521 int field_opts(FIELD *field); /* field to query */
1523 By default, all options are on. Here are the available option bits:
1526 Controls whether the field is visible on the screen. Can be
1527 used during form processing to hide or pop up fields depending
1528 on the value of parent fields.
1531 Controls whether the field is active during forms processing
1532 (i.e. visited by form navigation keys). Can be used to make
1533 labels or derived fields with buffer values alterable by the
1534 forms application, not the user.
1537 Controls whether data is displayed during field entry. If this
1538 option is turned off on a field, the library will accept and
1539 edit data in that field, but it will not be displayed and the
1540 visible field cursor will not move. You can turn off the
1541 O_PUBLIC bit to define password fields.
1544 Controls whether the field's data can be modified. When this
1545 option is off, all editing requests except REQ_PREV_CHOICE and
1546 REQ_NEXT_CHOICE will fail. Such read-only fields may be useful
1550 Controls word-wrapping in multi-line fields. Normally, when any
1551 character of a (blank-separated) word reaches the end of the
1552 current line, the entire word is wrapped to the next line
1553 (assuming there is one). When this option is off, the word will
1554 be split across the line break.
1557 Controls field blanking. When this option is on, entering a
1558 character at the first field position erases the entire field
1559 (except for the just-entered character).
1562 Controls automatic skip to next field when this one fills.
1563 Normally, when the forms user tries to type more data into a
1564 field than will fit, the editing location jumps to next field.
1565 When this option is off, the user's cursor will hang at the end
1566 of the field. This option is ignored in dynamic fields that
1567 have not reached their size limit.
1570 Controls whether validation is applied to blank fields.
1571 Normally, it is not; the user can leave a field blank without
1572 invoking the usual validation check on exit. If this option is
1573 off on a field, exit from it will invoke a validation check.
1576 Controls whether validation occurs on every exit, or only after
1577 the field is modified. Normally the latter is true. Setting
1578 O_PASSOK may be useful if your field's validation function may
1579 change during forms processing.
1582 Controls whether the field is fixed to its initial dimensions.
1583 If you turn this off, the field becomes dynamic and will
1584 stretch to fit entered data.
1586 A field's options cannot be changed while the field is currently
1587 selected. However, options may be changed on posted fields that are
1590 The option values are bit-masks and can be composed with logical-or in
1595 Every field has a status flag, which is set to FALSE when the field is
1596 created and TRUE when the value in field buffer 0 changes. This flag
1597 can be queried and set directly:
1598 int set_field_status(FIELD *field, /* field to alter */
1599 int status); /* mode to set */
1601 int field_status(FIELD *field); /* fetch mode of field */
1603 Setting this flag under program control can be useful if you use the
1604 same form repeatedly, looking for modified fields each time.
1606 Calling field_status() on a field not currently selected for input
1607 will return a correct value. Calling field_status() on a field that is
1608 currently selected for input may not necessarily give a correct field
1609 status value, because entered data is not necessarily copied to buffer
1610 zero before the exit validation check. To guarantee that the returned
1611 status value reflects reality, call field_status() either (1) in the
1612 field's exit validation check routine, (2) from the field's or form's
1613 initialization or termination hooks, or (3) just after a
1614 REQ_VALIDATION request has been processed by the forms driver.
1618 Each field structure contains one character pointer slot that is not
1619 used by the forms library. It is intended to be used by applications
1620 to store private per-field data. You can manipulate it with:
1621 int set_field_userptr(FIELD *field, /* field to alter */
1622 char *userptr); /* mode to set */
1624 char *field_userptr(FIELD *field); /* fetch mode of field */
1626 (Properly, this user pointer field ought to have (void *) type. The
1627 (char *) type is retained for System V compatibility.)
1629 It is valid to set the user pointer of the default field (with a
1630 set_field_userptr() call passed a NULL field pointer.) When a new
1631 field is created, the default-field user pointer is copied to
1632 initialize the new field's user pointer.
1634 Variable-Sized Fields
1636 Normally, a field is fixed at the size specified for it at creation
1637 time. If, however, you turn off its O_STATIC bit, it becomes dynamic
1638 and will automatically resize itself to accommodate data as it is
1639 entered. If the field has extra buffers associated with it, they will
1640 grow right along with the main input buffer.
1642 A one-line dynamic field will have a fixed height (1) but variable
1643 width, scrolling horizontally to display data within the field area as
1644 originally dimensioned and located. A multi-line dynamic field will
1645 have a fixed width, but variable height (number of rows), scrolling
1646 vertically to display data within the field area as originally
1647 dimensioned and located.
1649 Normally, a dynamic field is allowed to grow without limit. But it is
1650 possible to set an upper limit on the size of a dynamic field. You do
1651 it with this function:
1652 int set_max_field(FIELD *field, /* field to alter (may not be NULL) */
1653 int max_size); /* upper limit on field size */
1655 If the field is one-line, max_size is taken to be a column size limit;
1656 if it is multi-line, it is taken to be a line size limit. To disable
1657 any limit, use an argument of zero. The growth limit can be changed
1658 whether or not the O_STATIC bit is on, but has no effect until it is.
1660 The following properties of a field change when it becomes dynamic:
1661 * If there is no growth limit, there is no final position of the
1662 field; therefore O_AUTOSKIP and O_NL_OVERLOAD are ignored.
1663 * Field justification will be ignored (though whatever justification
1664 is set up will be retained internally and can be queried).
1665 * The dup_field() and link_field() calls copy dynamic-buffer sizes.
1666 If the O_STATIC option is set on one of a collection of links,
1667 buffer resizing will occur only when the field is edited through
1669 * The call field_info() will retrieve the original static size of
1670 the field; use dynamic_field_info() to get the actual dynamic
1675 By default, a field will accept any data that will fit in its input
1676 buffer. However, it is possible to attach a validation type to a
1677 field. If you do this, any attempt to leave the field while it
1678 contains data that does not match the validation type will fail. Some
1679 validation types also have a character-validity check for each time a
1680 character is entered in the field.
1682 A field's validation check (if any) is not called when
1683 set_field_buffer() modifies the input buffer, nor when that buffer is
1684 changed through a linked field.
1686 The form library provides a rich set of pre-defined validation types,
1687 and gives you the capability to define custom ones of your own. You
1688 can examine and change field validation attributes with the following
1690 int set_field_type(FIELD *field, /* field to alter */
1691 FIELDTYPE *ftype, /* type to associate */
1692 ...); /* additional arguments*/
1694 FIELDTYPE *field_type(FIELD *field); /* field to query */
1696 The validation type of a field is considered an attribute of the
1697 field. As with other field attributes, Also, doing set_field_type()
1698 with a NULL field default will change the system default for
1699 validation of newly-created fields.
1701 Here are the pre-defined validation types:
1705 This field type accepts alphabetic data; no blanks, no digits, no
1706 special characters (this is checked at character-entry time). It is
1708 int set_field_type(FIELD *field, /* field to alter */
1709 TYPE_ALPHA, /* type to associate */
1710 int width); /* maximum width of field */
1712 The width argument sets a minimum width of data. Typically you will
1713 want to set this to the field width; if it is greater than the field
1714 width, the validation check will always fail. A minimum width of zero
1715 makes field completion optional.
1719 This field type accepts alphabetic data and digits; no blanks, no
1720 special characters (this is checked at character-entry time). It is
1722 int set_field_type(FIELD *field, /* field to alter */
1723 TYPE_ALNUM, /* type to associate */
1724 int width); /* maximum width of field */
1726 The width argument sets a minimum width of data. As with TYPE_ALPHA,
1727 typically you will want to set this to the field width; if it is
1728 greater than the field width, the validation check will always fail. A
1729 minimum width of zero makes field completion optional.
1733 This type allows you to restrict a field's values to be among a
1734 specified set of string values (for example, the two-letter postal
1735 codes for U.S. states). It is set up with:
1736 int set_field_type(FIELD *field, /* field to alter */
1737 TYPE_ENUM, /* type to associate */
1738 char **valuelist; /* list of possible values */
1739 int checkcase; /* case-sensitive? */
1740 int checkunique); /* must specify uniquely? */
1742 The valuelist parameter must point at a NULL-terminated list of valid
1743 strings. The checkcase argument, if true, makes comparison with the
1744 string case-sensitive.
1746 When the user exits a TYPE_ENUM field, the validation procedure tries
1747 to complete the data in the buffer to a valid entry. If a complete
1748 choice string has been entered, it is of course valid. But it is also
1749 possible to enter a prefix of a valid string and have it completed for
1752 By default, if you enter such a prefix and it matches more than one
1753 value in the string list, the prefix will be completed to the first
1754 matching value. But the checkunique argument, if true, requires prefix
1755 matches to be unique in order to be valid.
1757 The REQ_NEXT_CHOICE and REQ_PREV_CHOICE input requests can be
1758 particularly useful with these fields.
1762 This field type accepts an integer. It is set up as follows:
1763 int set_field_type(FIELD *field, /* field to alter */
1764 TYPE_INTEGER, /* type to associate */
1765 int padding, /* # places to zero-pad to */
1766 int vmin, int vmax); /* valid range */
1768 Valid characters consist of an optional leading minus and digits. The
1769 range check is performed on exit. If the range maximum is less than or
1770 equal to the minimum, the range is ignored.
1772 If the value passes its range check, it is padded with as many leading
1773 zero digits as necessary to meet the padding argument.
1775 A TYPE_INTEGER value buffer can conveniently be interpreted with the C
1776 library function atoi(3).
1780 This field type accepts a decimal number. It is set up as follows:
1781 int set_field_type(FIELD *field, /* field to alter */
1782 TYPE_NUMERIC, /* type to associate */
1783 int padding, /* # places of precision */
1784 double vmin, double vmax); /* valid range */
1786 Valid characters consist of an optional leading minus and digits.
1787 possibly including a decimal point. If your system supports locale's,
1788 the decimal point character used must be the one defined by your
1789 locale. The range check is performed on exit. If the range maximum is
1790 less than or equal to the minimum, the range is ignored.
1792 If the value passes its range check, it is padded with as many
1793 trailing zero digits as necessary to meet the padding argument.
1795 A TYPE_NUMERIC value buffer can conveniently be interpreted with the C
1796 library function atof(3).
1800 This field type accepts data matching a regular expression. It is set
1802 int set_field_type(FIELD *field, /* field to alter */
1803 TYPE_REGEXP, /* type to associate */
1804 char *regexp); /* expression to match */
1806 The syntax for regular expressions is that of regcomp(3). The check
1807 for regular-expression match is performed on exit.
1809 Direct Field Buffer Manipulation
1811 The chief attribute of a field is its buffer contents. When a form has
1812 been completed, your application usually needs to know the state of
1813 each field buffer. You can find this out with:
1814 char *field_buffer(FIELD *field, /* field to query */
1815 int bufindex); /* number of buffer to query */
1817 Normally, the state of the zero-numbered buffer for each field is set
1818 by the user's editing actions on that field. It is sometimes useful to
1819 be able to set the value of the zero-numbered (or some other) buffer
1820 from your application:
1821 int set_field_buffer(FIELD *field, /* field to alter */
1822 int bufindex, /* number of buffer to alter */
1823 char *value); /* string value to set */
1825 If the field is not large enough and cannot be resized to a
1826 sufficiently large size to contain the specified value, the value will
1827 be truncated to fit.
1829 Calling field_buffer() with a null field pointer will raise an error.
1830 Calling field_buffer() on a field not currently selected for input
1831 will return a correct value. Calling field_buffer() on a field that is
1832 currently selected for input may not necessarily give a correct field
1833 buffer value, because entered data is not necessarily copied to buffer
1834 zero before the exit validation check. To guarantee that the returned
1835 buffer value reflects on-screen reality, call field_buffer() either
1836 (1) in the field's exit validation check routine, (2) from the field's
1837 or form's initialization or termination hooks, or (3) just after a
1838 REQ_VALIDATION request has been processed by the forms driver.
1842 As with field attributes, form attributes inherit a default from a
1843 system default form structure. These defaults can be queried or set by
1844 of these functions using a form-pointer argument of NULL.
1846 The principal attribute of a form is its field list. You can query and
1847 change this list with:
1848 int set_form_fields(FORM *form, /* form to alter */
1849 FIELD **fields); /* fields to connect */
1851 char *form_fields(FORM *form); /* fetch fields of form */
1853 int field_count(FORM *form); /* count connect fields */
1855 The second argument of set_form_fields() may be a NULL-terminated
1856 field pointer array like the one required by new_form(). In that case,
1857 the old fields of the form are disconnected but not freed (and
1858 eligible to be connected to other forms), then the new fields are
1861 It may also be null, in which case the old fields are disconnected
1862 (and not freed) but no new ones are connected.
1864 The field_count() function simply counts the number of fields
1865 connected to a given from. It returns -1 if the form-pointer argument
1868 Control of Form Display
1870 In the overview section, you saw that to display a form you normally
1871 start by defining its size (and fields), posting it, and refreshing
1872 the screen. There is an hidden step before posting, which is the
1873 association of the form with a frame window (actually, a pair of
1874 windows) within which it will be displayed. By default, the forms
1875 library associates every form with the full-screen window stdscr.
1877 By making this step explicit, you can associate a form with a declared
1878 frame window on your screen display. This can be useful if you want to
1879 adapt the form display to different screen sizes, dynamically tile
1880 forms on the screen, or use a form as part of an interface layout
1883 The two windows associated with each form have the same functions as
1884 their analogues in the menu library. Both these windows are painted
1885 when the form is posted and erased when the form is unposted.
1887 The outer or frame window is not otherwise touched by the form
1888 routines. It exists so the programmer can associate a title, a border,
1889 or perhaps help text with the form and have it properly refreshed or
1890 erased at post/unpost time. The inner window or subwindow is where the
1891 current form page is actually displayed.
1893 In order to declare your own frame window for a form, you will need to
1894 know the size of the form's bounding rectangle. You can get this
1896 int scale_form(FORM *form, /* form to query */
1897 int *rows, /* form rows */
1898 int *cols); /* form cols */
1900 The form dimensions are passed back in the locations pointed to by the
1901 arguments. Once you have this information, you can use it to declare
1902 of windows, then use one of these functions:
1903 int set_form_win(FORM *form, /* form to alter */
1904 WINDOW *win); /* frame window to connect */
1906 WINDOW *form_win(FORM *form); /* fetch frame window of form */
1908 int set_form_sub(FORM *form, /* form to alter */
1909 WINDOW *win); /* form subwindow to connect */
1911 WINDOW *form_sub(FORM *form); /* fetch form subwindow of form */
1913 Note that curses operations, including refresh(), on the form, should
1914 be done on the frame window, not the form subwindow.
1916 It is possible to check from your application whether all of a
1917 scrollable field is actually displayed within the menu subwindow. Use
1919 int data_ahead(FORM *form); /* form to be queried */
1921 int data_behind(FORM *form); /* form to be queried */
1923 The function data_ahead() returns TRUE if (a) the current field is
1924 one-line and has undisplayed data off to the right, (b) the current
1925 field is multi-line and there is data off-screen below it.
1927 The function data_behind() returns TRUE if the first (upper left hand)
1928 character position is off-screen (not being displayed).
1930 Finally, there is a function to restore the form window's cursor to
1931 the value expected by the forms driver:
1932 int pos_form_cursor(FORM *) /* form to be queried */
1934 If your application changes the form window cursor, call this function
1935 before handing control back to the forms driver in order to
1938 Input Processing in the Forms Driver
1940 The function form_driver() handles virtualized input requests for form
1941 navigation, editing, and validation requests, just as menu_driver does
1942 for menus (see the section on menu input handling).
1943 int form_driver(FORM *form, /* form to pass input to */
1944 int request); /* form request code */
1946 Your input virtualization function needs to take input and then
1947 convert it to either an alphanumeric character (which is treated as
1948 data to be entered in the currently-selected field), or a forms
1951 The forms driver provides hooks (through input-validation and
1952 field-termination functions) with which your application code can
1953 check that the input taken by the driver matched what was expected.
1955 Page Navigation Requests
1957 These requests cause page-level moves through the form, triggering
1958 display of a new form screen.
1961 Move to the next form page.
1964 Move to the previous form page.
1967 Move to the first form page.
1970 Move to the last form page.
1972 These requests treat the list as cyclic; that is, REQ_NEXT_PAGE from
1973 the last page goes to the first, and REQ_PREV_PAGE from the first page
1976 Inter-Field Navigation Requests
1978 These requests handle navigation between fields on the same page.
1984 Move to previous field.
1987 Move to the first field.
1990 Move to the last field.
1993 Move to sorted next field.
1996 Move to sorted previous field.
1999 Move to the sorted first field.
2002 Move to the sorted last field.
2008 Move right to field.
2016 These requests treat the list of fields on a page as cyclic; that is,
2017 REQ_NEXT_FIELD from the last field goes to the first, and
2018 REQ_PREV_FIELD from the first field goes to the last. The order of the
2019 fields for these (and the REQ_FIRST_FIELD and REQ_LAST_FIELD requests)
2020 is simply the order of the field pointers in the form array (as set up
2021 by new_form() or set_form_fields()
2023 It is also possible to traverse the fields as if they had been sorted
2024 in screen-position order, so the sequence goes left-to-right and
2025 top-to-bottom. To do this, use the second group of four
2026 sorted-movement requests.
2028 Finally, it is possible to move between fields using visual directions
2029 up, down, right, and left. To accomplish this, use the third group of
2030 four requests. Note, however, that the position of a form for purposes
2031 of these requests is its upper-left corner.
2033 For example, suppose you have a multi-line field B, and two
2034 single-line fields A and C on the same line with B, with A to the left
2035 of B and C to the right of B. A REQ_MOVE_RIGHT from A will go to B
2036 only if A, B, and C all share the same first line; otherwise it will
2039 Intra-Field Navigation Requests
2041 These requests drive movement of the edit cursor within the currently
2045 Move to next character.
2048 Move to previous character.
2054 Move to previous line.
2060 Move to previous word.
2063 Move to beginning of field.
2066 Move to end of field.
2069 Move to beginning of line.
2072 Move to end of line.
2078 Move right in field.
2086 Each word is separated from the previous and next characters by
2087 whitespace. The commands to move to beginning and end of line or field
2088 look for the first or last non-pad character in their ranges.
2092 Fields that are dynamic and have grown and fields explicitly created
2093 with offscreen rows are scrollable. One-line fields scroll
2094 horizontally; multi-line fields scroll vertically. Most scrolling is
2095 triggered by editing and intra-field movement (the library scrolls the
2096 field to keep the cursor visible). It is possible to explicitly
2097 request scrolling with the following requests:
2100 Scroll vertically forward a line.
2103 Scroll vertically backward a line.
2106 Scroll vertically forward a page.
2109 Scroll vertically backward a page.
2112 Scroll vertically forward half a page.
2115 Scroll vertically backward half a page.
2118 Scroll horizontally forward a character.
2121 Scroll horizontally backward a character.
2124 Scroll horizontally one field width forward.
2127 Scroll horizontally one field width backward.
2130 Scroll horizontally one half field width forward.
2133 Scroll horizontally one half field width backward.
2135 For scrolling purposes, a page of a field is the height of its visible
2140 When you pass the forms driver an ASCII character, it is treated as a
2141 request to add the character to the field's data buffer. Whether this
2142 is an insertion or a replacement depends on the field's edit mode
2143 (insertion is the default.
2145 The following requests support editing the field and changing the edit
2155 New line request (see below for explanation).
2158 Insert space at character location.
2161 Insert blank line at character location.
2164 Delete character at cursor.
2167 Delete previous word at cursor.
2170 Delete line at cursor.
2173 Delete word at cursor.
2176 Clear to end of line.
2179 Clear to end of field.
2184 The behavior of the REQ_NEW_LINE and REQ_DEL_PREV requests is
2185 complicated and partly controlled by a pair of forms options. The
2186 special cases are triggered when the cursor is at the beginning of a
2187 field, or on the last line of the field.
2189 First, we consider REQ_NEW_LINE:
2191 The normal behavior of REQ_NEW_LINE in insert mode is to break the
2192 current line at the position of the edit cursor, inserting the portion
2193 of the current line after the cursor as a new line following the
2194 current and moving the cursor to the beginning of that new line (you
2195 may think of this as inserting a newline in the field buffer).
2197 The normal behavior of REQ_NEW_LINE in overlay mode is to clear the
2198 current line from the position of the edit cursor to end of line. The
2199 cursor is then moved to the beginning of the next line.
2201 However, REQ_NEW_LINE at the beginning of a field, or on the last line
2202 of a field, instead does a REQ_NEXT_FIELD. O_NL_OVERLOAD option is
2203 off, this special action is disabled.
2205 Now, let us consider REQ_DEL_PREV:
2207 The normal behavior of REQ_DEL_PREV is to delete the previous
2208 character. If insert mode is on, and the cursor is at the start of a
2209 line, and the text on that line will fit on the previous one, it
2210 instead appends the contents of the current line to the previous one
2211 and deletes the current line (you may think of this as deleting a
2212 newline from the field buffer).
2214 However, REQ_DEL_PREV at the beginning of a field is instead treated
2215 as a REQ_PREV_FIELD.
2217 If the O_BS_OVERLOAD option is off, this special action is disabled
2218 and the forms driver just returns E_REQUEST_DENIED.
2220 See Form Options for discussion of how to set and clear the overload
2225 If the type of your field is ordered, and has associated functions for
2226 getting the next and previous values of the type from a given value,
2227 there are requests that can fetch that value into the field buffer:
2230 Place the successor value of the current value in the buffer.
2233 Place the predecessor value of the current value in the buffer.
2235 Of the built-in field types, only TYPE_ENUM has built-in successor and
2236 predecessor functions. When you define a field type of your own (see
2237 Custom Validation Types), you can associate our own ordering
2240 Application Commands
2242 Form requests are represented as integers above the curses value
2243 greater than KEY_MAX and less than or equal to the constant
2244 MAX_COMMAND. If your input-virtualization routine returns a value
2245 above MAX_COMMAND, the forms driver will ignore it.
2249 It is possible to set function hooks to be executed whenever the
2250 current field or form changes. Here are the functions that support
2252 typedef void (*HOOK)(); /* pointer to function returning void */
2254 int set_form_init(FORM *form, /* form to alter */
2255 HOOK hook); /* initialization hook */
2257 HOOK form_init(FORM *form); /* form to query */
2259 int set_form_term(FORM *form, /* form to alter */
2260 HOOK hook); /* termination hook */
2262 HOOK form_term(FORM *form); /* form to query */
2264 int set_field_init(FORM *form, /* form to alter */
2265 HOOK hook); /* initialization hook */
2267 HOOK field_init(FORM *form); /* form to query */
2269 int set_field_term(FORM *form, /* form to alter */
2270 HOOK hook); /* termination hook */
2272 HOOK field_term(FORM *form); /* form to query */
2274 These functions allow you to either set or query four different hooks.
2275 In each of the set functions, the second argument should be the
2276 address of a hook function. These functions differ only in the timing
2280 This hook is called when the form is posted; also, just after
2281 each page change operation.
2284 This hook is called when the form is posted; also, just after
2288 This hook is called just after field validation; that is, just
2289 before the field is altered. It is also called when the form is
2293 This hook is called when the form is unposted; also, just
2294 before each page change operation.
2296 Calls to these hooks may be triggered
2297 1. When user editing requests are processed by the forms driver
2298 2. When the current page is changed by set_current_field() call
2299 3. When the current field is changed by a set_form_page() call
2301 See Field Change Commands for discussion of the latter two cases.
2303 You can set a default hook for all fields by passing one of the set
2304 functions a NULL first argument.
2306 You can disable any of these hooks by (re)setting them to NULL, the
2309 Field Change Commands
2311 Normally, navigation through the form will be driven by the user's
2312 input requests. But sometimes it is useful to be able to move the
2313 focus for editing and viewing under control of your application, or
2314 ask which field it currently is in. The following functions help you
2316 int set_current_field(FORM *form, /* form to alter */
2317 FIELD *field); /* field to shift to */
2319 FIELD *current_field(FORM *form); /* form to query */
2321 int field_index(FORM *form, /* form to query */
2322 FIELD *field); /* field to get index of */
2324 The function field_index() returns the index of the given field in the
2325 given form's field array (the array passed to new_form() or
2328 The initial current field of a form is the first active field on the
2329 first page. The function set_form_fields() resets this.
2331 It is also possible to move around by pages.
2332 int set_form_page(FORM *form, /* form to alter */
2333 int page); /* page to go to (0-origin) */
2335 int form_page(FORM *form); /* return form's current page */
2337 The initial page of a newly-created form is 0. The function
2338 set_form_fields() resets this.
2342 Like fields, forms may have control option bits. They can be changed
2343 or queried with these functions:
2344 int set_form_opts(FORM *form, /* form to alter */
2345 int attr); /* attribute to set */
2347 int form_opts_on(FORM *form, /* form to alter */
2348 int attr); /* attributes to turn on */
2350 int form_opts_off(FORM *form, /* form to alter */
2351 int attr); /* attributes to turn off */
2353 int form_opts(FORM *form); /* form to query */
2355 By default, all options are on. Here are the available option bits:
2358 Enable overloading of REQ_NEW_LINE as described in Editing
2359 Requests. The value of this option is ignored on dynamic fields
2360 that have not reached their size limit; these have no last
2361 line, so the circumstances for triggering a REQ_NEXT_FIELD
2365 Enable overloading of REQ_DEL_PREV as described in Editing
2368 The option values are bit-masks and can be composed with logical-or in
2371 Custom Validation Types
2373 The form library gives you the capability to define custom validation
2374 types of your own. Further, the optional additional arguments of
2375 set_field_type effectively allow you to parameterize validation types.
2376 Most of the complications in the validation-type interface have to do
2377 with the handling of the additional arguments within custom validation
2382 The simplest way to create a custom data type is to compose it from
2383 two preexisting ones:
2384 FIELD *link_fieldtype(FIELDTYPE *type1,
2387 This function creates a field type that will accept any of the values
2388 legal for either of its argument field types (which may be either
2389 predefined or programmer-defined). If a set_field_type() call later
2390 requires arguments, the new composite type expects all arguments for
2391 the first type, than all arguments for the second. Order functions
2392 (see Order Requests) associated with the component types will work on
2393 the composite; what it does is check the validation function for the
2394 first type, then for the second, to figure what type the buffer
2395 contents should be treated as.
2399 To create a field type from scratch, you need to specify one or both
2400 of the following things:
2401 * A character-validation function, to check each character as it is
2403 * A field-validation function to be applied on exit from the field.
2405 Here is how you do that:
2406 typedef int (*HOOK)(); /* pointer to function returning int */
2408 FIELDTYPE *new_fieldtype(HOOK f_validate, /* field validator */
2409 HOOK c_validate) /* character validator */
2411 int free_fieldtype(FIELDTYPE *ftype); /* type to free */
2413 At least one of the arguments of new_fieldtype() must be non-NULL. The
2414 forms driver will automatically call the new type's validation
2415 functions at appropriate points in processing a field of the new type.
2417 The function free_fieldtype() deallocates the argument fieldtype,
2418 freeing all storage associated with it.
2420 Normally, a field validator is called when the user attempts to leave
2421 the field. Its first argument is a field pointer, from which it can
2422 get to field buffer 0 and test it. If the function returns TRUE, the
2423 operation succeeds; if it returns FALSE, the edit cursor stays in the
2426 A character validator gets the character passed in as a first
2427 argument. It too should return TRUE if the character is valid, FALSE
2430 Validation Function Arguments
2432 Your field- and character- validation functions will be passed a
2433 second argument as well. This second argument is the address of a
2434 structure (which we will call a pile) built from any of the
2435 field-type-specific arguments passed to set_field_type(). If no such
2436 arguments are defined for the field type, this pile pointer argument
2439 In order to arrange for such arguments to be passed to your validation
2440 functions, you must associate a small set of storage-management
2441 functions with the type. The forms driver will use these to synthesize
2442 a pile from the trailing arguments of each set_field_type() argument,
2443 and a pointer to the pile will be passed to the validation functions.
2445 Here is how you make the association:
2446 typedef char *(*PTRHOOK)(); /* pointer to function returning (char *) */
2447 typedef void (*VOIDHOOK)(); /* pointer to function returning void */
2449 int set_fieldtype_arg(FIELDTYPE *type, /* type to alter */
2450 PTRHOOK make_str, /* make structure from args */
2451 PTRHOOK copy_str, /* make copy of structure */
2452 VOIDHOOK free_str); /* free structure storage */
2454 Here is how the storage-management hooks are used:
2457 This function is called by set_field_type(). It gets one
2458 argument, a va_list of the type-specific arguments passed to
2459 set_field_type(). It is expected to return a pile pointer to a
2460 data structure that encapsulates those arguments.
2463 This function is called by form library functions that allocate
2464 new field instances. It is expected to take a pile pointer,
2465 copy the pile to allocated storage, and return the address of
2469 This function is called by field- and type-deallocation
2470 routines in the library. It takes a pile pointer argument, and
2471 is expected to free the storage of that pile.
2473 The make_str and copy_str functions may return NULL to signal
2474 allocation failure. The library routines will that call them will
2475 return error indication when this happens. Thus, your validation
2476 functions should never see a NULL file pointer and need not check
2479 Order Functions For Custom Types
2481 Some custom field types are simply ordered in the same well-defined
2482 way that TYPE_ENUM is. For such types, it is possible to define
2483 successor and predecessor functions to support the REQ_NEXT_CHOICE and
2484 REQ_PREV_CHOICE requests. Here is how:
2485 typedef int (*INTHOOK)(); /* pointer to function returning int */
2487 int set_fieldtype_arg(FIELDTYPE *type, /* type to alter */
2488 INTHOOK succ, /* get successor value */
2489 INTHOOK pred); /* get predecessor value */
2491 The successor and predecessor arguments will each be passed two
2492 arguments; a field pointer, and a pile pointer (as for the validation
2493 functions). They are expected to use the function field_buffer() to
2494 read the current value, and set_field_buffer() on buffer 0 to set the
2495 next or previous value. Either hook may return TRUE to indicate
2496 success (a legal next or previous value was set) or FALSE to indicate
2501 The interface for defining custom types is complicated and tricky.
2502 Rather than attempting to create a custom type entirely from scratch,
2503 you should start by studying the library source code for whichever of
2504 the pre-defined types seems to be closest to what you want.
2506 Use that code as a model, and evolve it towards what you really want.
2507 You will avoid many problems and annoyances that way. The code in the
2508 ncurses library has been specifically exempted from the package
2509 copyright to support this.
2511 If your custom type defines order functions, have do something
2512 intuitive with a blank field. A useful convention is to make the
2513 successor of a blank field the types minimum value, and its
2514 predecessor the maximum.