ncurses(3X) | Library calls | ncurses(3X) |
ncurses - character-cell terminal interface with optimized output
#include <ncurses/curses.h>
The “new curses” library offers the programmer a terminal-independent means of reading keyboard and mouse input and updating character-cell terminals with output optimized to minimize screen updates. ncurses replaces the curses libraries from System V Release 4 Unix (“SVr4”) and 4.4BSD Unix, the development of which ceased in the 1990s. This document describes ncurses version 6.5 (patch 20240511).
ncurses permits control of the terminal screen's contents; abstraction and subdivision thereof with windows and pads; acquisition of keyboard and mouse events; control of terminal input and output options; selection of color and rendering attributes (such as bold or underline); the definition and use of soft label keys; access to the terminfo terminal capability database; a termcap compatibility interface; and an abstraction of the system's API for manipulating the terminal (such as termios(3)).
ncurses implements the interface described by X/Open Curses Issue 7. In many behavioral details not standardized by X/Open, ncurses emulates the curses library of SVr4 and provides numerous useful extensions.
ncurses man pages employ several sections to clarify matters of usage and interoperability with other curses implementations.
A curses application must be linked with the library; use the -lncurses option to your compiler or linker. A debugging version of the library may be available; if so, link with it using -lncurses_g. (Your system integrator may have installed these libraries such that you can use the options -lcurses and -lcurses_g, respectively.) The ncurses_g library generates trace logs (in a file called trace in the current directory) that describe ncurses actions. See section “ALTERNATE CONFIGURATIONS” below.
A curses application uses information from the system locale; setlocale(3) prepares it for curses library calls.
setlocale(LC_ALL, "");
If the locale is not thus initialized, the library assumes that characters are printable as in ISO 8859-1, to work with certain legacy programs. You should initialize the locale; do not expect consistent behavior from the library when the locale has not been set up.
initscr(3X) or newterm(3X) must be called to initialize curses before use of any functions that deal with windows and screens.
To get character-at-a-time input without echoing—most interactive, screen-oriented programs want this—use the following sequence.
initscr(); cbreak(); noecho();
Most applications perform further setup as follows.
intrflush(stdscr, FALSE); keypad(stdscr, TRUE);
A curses program then often enters an event loop of some sort. Call endwin(3X) before exiting.
A curses library abstracts the terminal screen by representing all or part of it as a WINDOW data structure. A window is a rectangular grid of character cells, addressed by row and column coordinates (y, x), with the upper left corner as (0, 0). A window called stdscr, the same size as the terminal screen, is always available. Create others with newwin(3X).
A curses library does not manage overlapping windows (but see below). You can either use stdscr to manage one screen-filling window, or tile the screen into non-overlapping windows and not use stdscr at all. Mixing the two approaches will result in unpredictable and undesired effects.
Functions permit manipulation of a window and the cursor identifying the cell within it at which the next output operation will occur. Among those, the most basic are move(3X) and addch(3X): these place the cursor and write a character to stdscr, respectively.
Frequent changes to the terminal screen can cause unpleasant flicker or inefficient use of the communication channel to the device, so as a rule the library does not update it automatically. Therefore, after using curses functions to accumulate a set of desired updates that make sense to present together, call refresh(3X) to tell the library to make the user's screen look like stdscr. The library optimizes its output by computing a minimal volume of operations to mutate the screen from its state at the previous refresh to the new one. Effective optimization demands accurate information about the terminal device: the management of such information is the province of the terminfo(3X) API, a feature of every standard curses implementation.
Special windows called pads may also be manipulated. These are not constrained to the size of the terminal screen and their contents need not be completely displayed. See curs_pad(3X).
Many terminals support configuration of character cell foreground and background colors as well as rendering attributes , which cause characters to show up in such modes as boldfaced, underlined, or in reverse video. See curs_attr(3X).
curses predefines constants for a small set of forms-drawing graphics corresponding to the DEC Alternate Character Set (ACS), a feature of VT100 and other terminals. See addch(3X).
curses is implemented using the operating system's terminal driver; key events are received not as scan codes but as byte sequences. Graphical keycaps (alphanumeric and punctuation keys, and the space) appear as-is. Everything else, including the tab, enter/return, keypad, arrow, and function keys, appears as a control character or a multibyte escape sequence. curses translates the latter into unique key codes. See getch(3X).
ncurses provides reimplementations of the SVr4 panel(3X), form(3X), and menu(3X) libraries; they permit overlapping windows and ease construction of user interfaces with curses.
The selection of an appropriate value of TERM in the process environment is essential to correct curses and terminfo library operation. A well-configured system selects a correct TERM value automatically; tset(1) may assist with troubleshooting exotic situations.
If you change the terminal type, export the shell's TERM variable, then run tset(1) or the “gtput init” command. See subsection “Tabs and Initialization” of terminfo(5).
If the environment variables LINES and COLUMNS are set, or if the curses program is executing in a graphical windowing environment, the information obtained thence overrides that obtained by terminfo. An ncurses extension supports resizable terminals; see wresize(3X).
If the environment variable TERMINFO is defined, a curses program checks first for a terminal type description in the location it identifies. TERMINFO is useful for developing type descriptions or when write permission to /usr/gnu/share/terminfo is not available.
See section “ENVIRONMENT” below.
curses offers many functions in variant forms using a regular set of alternatives to the name of an elemental one. Those prefixed with “w” require a WINDOW pointer argument; those with a “mv” prefix first perform cursor movement using wmove(3X); a “mvw” prefix indicates both. The “w” function is typically the elemental one; the removal of this prefix usually indicates operation on stdscr.
Four functions prefixed with “p” require a pad argument.
In function synopses, ncurses man pages apply the following names to parameters.
bf | a bool (TRUE or FALSE) |
c | a char or int |
ch | a chtype |
wc | a wchar_t or wint_t |
wch | a cchar_t |
win | pointer to a WINDOW |
pad | pointer to a WINDOW that is a pad |
This man page primarily surveys functions that appear in any configuration of the library. There are two common configurations; see section “ALTERNATE CONFIGURATIONS” below.
Each cell of a WINDOW is stored as a cchar_t.
setcchar(3X) and getcchar(3X) store and retrieve cchar_t data. The wide library API of ncurses depends on two data types standardized by ISO C95.
The following table lists the curses functions provided in the non-wide and wide APIs and the corresponding man pages that describe them. Those flagged with “*” are ncurses-specific, neither described by X/Open Curses nor present in SVr4.
ncurses's screen-pointer extension adds additional functions corresponding to many of the above, each with an “_sp” suffix; see curs_sp_funcs(3X).
The availability of some extensions is configurable when ncurses is compiled; see sections “ALTERNATE CONFIGURATIONS” and “EXTENSIONS” below.
Unless otherwise noted, functions that return integers return the constants OK on success and ERR on failure; see curs_variables(3X). Functions that return pointers return NULL on failure. Typically, ncurses treats a null pointer passed as a function parameter as a failure. Functions prefixed with “mv” first perform cursor movement and fail if the position (y, x) is outside the window boundaries.
The following symbols from the process environment customize the runtime behavior of ncurses applications. The library may be configured to disregard the variables TERMINFO, TERMINFO_DIRS, TERMPATH, and HOME, if the user is the superuser (root), or the application uses setuid(2) or setgid(2).
The debugging library checks this variable when the application has redirected output to a file. Its integral value is used for the baud rate. If that value is absent or invalid, ncurses uses 9600. This feature allows developers to construct repeatable test cases that take into account optimization decisions that depend on baud rate.
When set, the command_character (cmdch) capability value of loaded terminfo entries changes to the value of this variable. Very few terminfo entries provide this feature.
Because this name is also used in development environments to represent the C compiler's name, ncurses ignores its value if it is not one character in length.
This variable specifies the width of the screen in characters. Applications running in a windowing environment usually are able to obtain the width of the window in which they are executing. If COLUMNS is not defined and the terminal's screen size is not available from the terminal driver, ncurses uses the size specified by the columns (cols) capability of the terminal type's entry in the terminfo database, if any.
It is important that your application use the correct screen size. Automatic detection thereof is not always possible because an application may be running on a host that does not honor NAWS (Negotiations About Window Size) or as a different user ID than the owner of the terminal device file. Setting COLUMNS and/or LINES overrides the library's use of the screen size obtained from the operating system.
The COLUMNS and LINES variables may be specified independently. This property is useful to circumvent misfeatures of legacy terminal type descriptions; xterm(1) descriptions specifying 65 lines were once notorious. For best results, avoid specifying cols and lines capability codes in terminfo descriptions of terminal emulators.
use_env(3X) can disable use of the process environment in determining the screen size. use_tioctl(3X) can update COLUMNS and LINES to match the screen size obtained from system calls or the terminal database.
For curses to distinguish the ESC character resulting from a user's press of the “Escape” key on the input device from one beginning an escape sequence (as commonly produced by function keys), it waits after receiving the escape character to see if further characters are available on the input stream within a short interval. A global variable ESCDELAY stores this interval in milliseconds. The default value of 1000 (one second) is adequate for most uses. This environment variable overrides it.
The most common instance where you may wish to change this value is to work with a remote host over a slow communication channel. If the host running a curses application does not receive the characters of an escape sequence in a timely manner, the library can interpret them as multiple key stroke events.
xterm(1) mouse events are a form of escape sequence; therefore, if your application makes heavy use of multiple-clicking, you may wish to lengthen the default value because the delay applies to the composite multi-click event as well as the individual clicks.
Portable applications should not rely upon the presence of ESCDELAY in either form, but setting the environment variable rather than the global variable does not create problems when compiling an application.
If keypad(3X) is disabled for the curses window receiving input, a program must disambiguate escape sequences itself.
ncurses may read and write auxiliary terminal descriptions in .termcap and .terminfo files in the user's home directory.
This counterpart to COLUMNS specifies the height of the screen in characters. The corresponding terminfo capability and code is lines. See the description of the COLUMNS variable above.
(OS/2 EMX port only) OS/2 numbers a three-button mouse inconsistently with other platforms, such that 1 is the left button, 2 the right, and 3 the middle. This variable customizes the mouse button numbering. Its value must be three digits 1-3 in any order. By default, ncurses assumes a numbering of “132”.
If set, this variable overrides the ncurses library's compiled-in assumption that the terminal's default colors are white on black; see default_colors(3X). Set the foreground and background color values with this environment variable by assigning it two integer values separated by a comma, indicating foregound and background color numbers, respectively.
For example, to tell ncurses not to assume anything about the colors, use a value of “-1,-1”. To make the default color scheme green on black, use “2,0”. ncurses accepts integral values from -1 up to the value of the terminfo max_colors (colors) capability.
(MinGW port only) The Console2 program defectively handles the Microsoft Console API call CreateConsoleScreenBuffer. Applications that use it will hang. However, it is possible to simulate the action of this call by mapping coordinates, explicitly saving and restoring the original screen contents. Setting the environment variable NCGDB has the same effect.
(Linux only) When ncurses is configured to use the GPM interface, this variable may list one or more terminal type names against which the TERM variable (see below) is matched. An empty value disables the GPM interface, using ncurses's built-in support for xterm(1) mouse protocols instead. If the variable is absent, ncurses attempts to open GPM if TERM contains “linux”.
ncurses may use tab characters in cursor movement optimization. In some cases, your terminal driver may not handle them properly. Set this environment variable to any value to disable the feature. You can also adjust your stty(1) settings to avoid the problem.
Many terminals store video attributes as a property of a character cell, as curses does. Historically, some recorded changes in video attributes as data that logically occupies character cells on the display, switching attributes on or off, similarly to tags in a markup language; these are termed “magic cookies”, and must be subsequently overprinted. If the terminfo entry for your terminal type does not adequately describe its handling of magic cookies, set this variable to any value to instruct ncurses to disable attributes entirely.
Most terminal type descriptions in the terminfo database detail hardware devices. Many people use curses-based applications in terminal emulator programs that run in a windowing environment. These programs can duplicate all of the important features of a hardware terminal, but often lack their limitations. Chief among these absent drawbacks is the problem of data flow management; that is, limiting the speed of communication to what the hardware could handle. Unless a hardware terminal is interfaced into a terminal concentrator (which does flow control), an application must manage flow itself to prevent overruns and data loss.
A solution that comes at no hardware cost is for an application to pause after directing a terminal to execute an operation that it performs slowly, such as clearing the display. Many terminal type descriptions, including that for the VT100, embed delay specifications in capabilities. You may wish to use these terminal descriptions without paying the performance penalty. Set NCURSES_NO_PADDING to any value to disable all but mandatory padding. Mandatory padding is used by such terminal capabilities as flash_screen (flash).
(Obsolete) Prior to internal changes developed in ncurses 5.9 (patches 20120825 through 20130126), the library used setbuf(3) to enable fully buffered output when initializing the terminal. This was done, as in SVr4 curses, to increase performance. For testing purposes, both of ncurses and of certain applications, this feature was made optional. Setting this variable disabled output buffering, leaving the output stream in the original (usually line-buffered) mode.
Nowadays, ncurses performs its own buffering and does not require this workaround; it does not modify the buffering of the standard output stream. This approach makes signal handling, as for interrupts, more robust. A drawback is that certain unconventional programs mixed stdio(3) calls with ncurses calls and (usually) got the behavior they expected. This is no longer the case; ncurses does not write to the standard output file descriptor through a stdio-buffered stream.
As a special case, low-level API calls such as putp(3X) still use the standard output stream. High-level curses calls such as printw(3X) do not.
At initialization, ncurses inspects the TERM environment variable for special cases where VT100 forms-drawing characters (and the corresponding alternate character set terminfo capabilities) are known to be unsupported by terminal types that otherwise claim VT100 compatibility. Specifically, when running in a UTF-8 locale, the Linux virtual console device and the GNU screen(1) program ignore them. Set this variable to a nonzero value to instruct ncurses that the terminal's ACS support is broken; the library then outputs Unicode code points that correspond to the forms-drawing characters. Set it to zero (or a non-integer) to disable the special check for terminal type names matching “linux” or “screen”, directing ncurses to assume that the ACS feature works if the terminal type description advertises it.
As an alternative to use of this variable, ncurses checks for an extended terminfo numeric capability U8 that can be compiled using “gtic -x”. Examples follow.
# linux console, if patched to provide working # VT100 shift-in/shift-out, with corresponding font. linux-vt100|linux console with VT100 line-graphics,
U8#0, use=linux, # uxterm with vt100Graphics resource set to false xterm-utf8|xterm relying on UTF-8 line-graphics,
U8#1, use=xterm,
The two-character name “U8” was chosen to permit its use via ncurses's termcap interface.
At initialization, ncurses (in its debugging configuration) checks for this variable's presence. If defined with an integral value, the library calls curses_trace(3X) with that value as the argument.
The TERM variable denotes the terminal type. Each is distinct, though many are similar. It is commonly set by terminal emulators to help applications find a workable terminal description. Some choose a popular approximation such as “ansi”, “vt100”, or “xterm” rather than an exact fit to their capabilities. Not infrequently, an application will have problems with that approach; for example, a key stroke may not operate correctly, or produce no effect but seeming garbage characters on the screen.
Setting TERM has no effect on hardware operation; it affects the way applications communicate with the terminal. Likewise, as a general rule (xterm(1) being a rare exception), terminal emulators that allow you to specify TERM as a parameter or configuration value do not change their behavior to match that setting.
If ncurses is configured with termcap support, it checks for a terminal type description in termcap format if one in terminfo format is not available. Setting this variable directs ncurses to ignore the usual termcap database location, /etc/termcap; see TERMPATH below. TERMCAP should contain either a terminal description (with newlines stripped out), or a file name indicating where the information required by the TERM environment variable is stored.
ncurses can be configured to read terminal type description databases in various locations using different formats. This variable overrides the default location.
The hashed database uses less disk space and is a little faster than the directory tree. However, some applications assume the existence of the directory tree, and read it directly rather than using the terminfo API.
TERMINFO=$(infocmp -0 -Q2 -q) export TERMINFO
Setting TERMINFO is the simplest, but not the only, way to direct ncurses to a terminal database. The search path is as follows.
This variable specifies a list of locations, akin to PATH, in which ncurses searches for the terminal type descriptions described by TERMINFO above. The list items are separated by colons on Unix and semicolons on OS/2 EMX. System V terminfo lacks a corresponding feature; TERMINFO_DIRS is an ncurses extension.
If TERMCAP does not hold a terminal type description or file name, then ncurses checks the contents of TERMPATH, a list of locations, akin to PATH, in which it searches for termcap terminal type descriptions. The list items are separated by colons on Unix and semicolons on OS/2 EMX.
If both TERMCAP and TERMPATH are unset or invalid, ncurses searches for the files /etc/termcap, /usr/share/misc/termcap, and $HOME/.termcap, in that order.
Many different ncurses configurations are possible, determined by the options given to the configure script when building the library. Run the script with the --help option to peruse them all. A few are of particular significance to the application developer employing ncurses.
#include <curses.h>
This option is used to avoid file name conflicts between ncurses and an existing curses installation on the system. If ncurses is installed disabling overwrite, it puts its header files in a subdirectory. Here is an example.
#include <ncurses/curses.h>
Installation also omits a symbolic link that would cause the compiler's -lcurses option to link object files with ncurses instead of the system curses library.
The directory used by this configuration of ncurses is shown in section “SYNOPSIS” above.
-lncurses
you link with
-lncursesw
You must also enable the wide-character features in the header file when compiling for the wide-character library to use the extended (wide-character) functions. The symbol which enables these features has changed since X/Open Curses, Issue 4:
The curses.h header file installed for the wide-character library is designed to be compatible with the non-wide library's header. Only the size of the WINDOW structure differs; few applications require more than pointers to WINDOWs.
If the headers are installed allowing overwrite, the wide-character library's headers should be installed last, to allow applications to be built using either library from the same set of headers.
X/Open Curses permits most functions it specifies to be made available as macros as well. ncurses does so
If the standard output file descriptor of an ncurses program is redirected to something that is not a terminal device, the library writes screen updates to the standard error file descriptor. This was an undocumented feature of SVr3 curses.
See subsection “Header Files” below regarding symbols exposed by inclusion of curses.h.
ncurses enables an application to capture mouse events on certain terminals, including xterm(1); see curs_mouse(3X).
ncurses provides a means of responding to window resizing events, as when running in a GUI terminal emulator application such as xterm; see resizeterm(3X) and wresize(3X).
ncurses allows an application to query the terminal for the presence of a wide variety of special keys; see has_key(3X).
ncurses extends the fixed set of function key capabilities specified by X/Open Curses by allowing the application programmer to define additional key events at runtime; see define_key(3X), key_defined(3X), keybound(3X), and keyok(3X).
ncurses can exploit the capabilities of terminals implementing ISO 6429/ECMA-48 SGR 39 and SGR 49 sequences, which allow an application to reset the terminal to its original foreground and background colors. From a user's perspective, the application is able to draw colored text on a background whose color is set independently, providing better control over color contrasts. See default_colors(3X).
An ncurses application can eschew knowledge of WINDOW structure internals, instead using accessor functions such as is_scrollok(3X).
ncurses enables an application to direct its output to a printer attached to the terminal device; see curs_print(3X).
ncurses offers slk_attr(3X) as a counterpart of attr_get(3X) for soft-label key lines, and extended_slk_color(3X) as a form of slk_color(3X) that can gather color information from them when many colors are supported.
Some extensions are available only if ncurses permits modification of unctrl(3X)'s behavior; see use_legacy_coding(3X). ncurses is compiled to support them; section “ALTERNATE CONFIGURATIONS” describes how.
ncurses permits modification of unctrl(3X)'s behavior; see use_legacy_coding(3X).
Rudimentary support for multi-threaded applications may be available; see curs_threads(3X).
Functions that ease the management of multiple screens can be exposed; see curs_sp_funcs(3X).
To aid applications to debug their memory usage, ncurses optionally offers functions to more aggressively free memory it dynamically allocates itself; see curs_memleaks(3X).
The library facilitates auditing and troubleshooting of its behavior; see curs_trace(3X).
Compiling ncurses with the option -DUSE_GETCAP causes it to fall back to reading /etc/termcap if the terminal setup code cannot find a terminfo entry corresponding to TERM. Use of this feature is not recommended, as it essentially includes an entire termcap compiler in the ncurses startup code, at a cost in memory usage and application launch latency.
PDCurses and NetBSD curses incorporate some ncurses extensions. Individual man pages indicate where this is the case.
X/Open Curses defines two levels of conformance, “base” and “enhanced”. The latter includes several additional features, such as wide-character and color support. ncurses intends base-level conformance with X/Open Curses, and supports all features of its enhanced level except the untic utility.
Differences between X/Open Curses and ncurses are documented in the “PORTABILITY” sections of applicable man pages.
In many cases, X/Open Curses is vague about error conditions, omitting some of the SVr4 documentation.
Unlike other implementations, ncurses checks pointer parameters, such as those to WINDOW structures, to ensure that they are not null. This is done primarily to guard against programmer error. The standard interface does not provide a way for the library to tell an application which of several possible errors occurred. An application that relies on ncurses to check its function parameters for validity limits its portability and robustness.
In historical curses implementations, delays embedded in the terminfo capabilities carriage_return (cr), scroll_forward (ind), cursor_left (cub1), form_feed (ff), and tab (ht) activated corresponding delay bits in the Unix terminal driver. ncurses performs all padding by sending NUL bytes to the device. This method is slightly more expensive, but narrows the interface to the Unix kernel significantly and correspondingly increases the package's portability.
The header file curses.h itself includes the header files stdio.h and unctrl.h.
X/Open Curses has more to say,
The inclusion of curses.h may make visible all symbols from the headers stdio.h, term.h, termios.h, and wchar.h.
but does not finish the story. A more complete account follows.
Zeyd M. Ben-Halim, Eric S. Raymond, Thomas E. Dickey. Based on pcurses by Pavel Curtis.
2024-05-11 | ncurses 6.5 |