• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`curses` --- Terminal handling for character-cell displays
2===============================================================
3
4.. module:: curses
5   :synopsis: An interface to the curses library, providing portable
6              terminal handling.
7   :platform: Unix
8
9.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
10.. sectionauthor:: Eric Raymond <esr@thyrsus.com>
11
12--------------
13
14The :mod:`curses` module provides an interface to the curses library, the
15de-facto standard for portable advanced terminal handling.
16
17While curses is most widely used in the Unix environment, versions are available
18for Windows, DOS, and possibly other systems as well.  This extension module is
19designed to match the API of ncurses, an open-source curses library hosted on
20Linux and the BSD variants of Unix.
21
22.. note::
23
24   Whenever the documentation mentions a *character* it can be specified
25   as an integer, a one-character Unicode string or a one-byte byte string.
26
27   Whenever the documentation mentions a *character string* it can be specified
28   as a Unicode string or a byte string.
29
30.. note::
31
32   Since version 5.4, the ncurses library decides how to interpret non-ASCII data
33   using the ``nl_langinfo`` function.  That means that you have to call
34   :func:`locale.setlocale` in the application and encode Unicode strings
35   using one of the system's available encodings.  This example uses the
36   system's default encoding::
37
38      import locale
39      locale.setlocale(locale.LC_ALL, '')
40      code = locale.getpreferredencoding()
41
42   Then use *code* as the encoding for :meth:`str.encode` calls.
43
44.. seealso::
45
46   Module :mod:`curses.ascii`
47      Utilities for working with ASCII characters, regardless of your locale settings.
48
49   Module :mod:`curses.panel`
50      A panel stack extension that adds depth to  curses windows.
51
52   Module :mod:`curses.textpad`
53      Editable text widget for curses supporting  :program:`Emacs`\ -like bindings.
54
55   :ref:`curses-howto`
56      Tutorial material on using curses with Python, by Andrew Kuchling and Eric
57      Raymond.
58
59   The :source:`Tools/demo/` directory in the Python source distribution contains
60   some example programs using the curses bindings provided by this module.
61
62
63.. _curses-functions:
64
65Functions
66---------
67
68The module :mod:`curses` defines the following exception:
69
70
71.. exception:: error
72
73   Exception raised when a curses library function returns an error.
74
75.. note::
76
77   Whenever *x* or *y* arguments to a function or a method are optional, they
78   default to the current cursor location. Whenever *attr* is optional, it defaults
79   to :const:`A_NORMAL`.
80
81The module :mod:`curses` defines the following functions:
82
83
84.. function:: baudrate()
85
86   Return the output speed of the terminal in bits per second.  On software
87   terminal emulators it will have a fixed high value. Included for historical
88   reasons; in former times, it was used to  write output loops for time delays and
89   occasionally to change interfaces depending on the line speed.
90
91
92.. function:: beep()
93
94   Emit a short attention sound.
95
96
97.. function:: can_change_color()
98
99   Return ``True`` or ``False``, depending on whether the programmer can change the colors
100   displayed by the terminal.
101
102
103.. function:: cbreak()
104
105   Enter cbreak mode.  In cbreak mode (sometimes called "rare" mode) normal tty
106   line buffering is turned off and characters are available to be read one by one.
107   However, unlike raw mode, special characters (interrupt, quit, suspend, and flow
108   control) retain their effects on the tty driver and calling program.  Calling
109   first :func:`raw` then :func:`cbreak` leaves the terminal in cbreak mode.
110
111
112.. function:: color_content(color_number)
113
114   Return the intensity of the red, green, and blue (RGB) components in the color
115   *color_number*, which must be between ``0`` and ``COLORS - 1``.  Return a 3-tuple,
116   containing the R,G,B values for the given color, which will be between
117   ``0`` (no component) and ``1000`` (maximum amount of component).
118
119
120.. function:: color_pair(pair_number)
121
122   Return the attribute value for displaying text in the specified color pair.
123   Only the first 256 color pairs are supported. This
124   attribute value can be combined with :const:`A_STANDOUT`, :const:`A_REVERSE`,
125   and the other :const:`A_\*` attributes.  :func:`pair_number` is the counterpart
126   to this function.
127
128
129.. function:: curs_set(visibility)
130
131   Set the cursor state.  *visibility* can be set to ``0``, ``1``, or ``2``, for invisible,
132   normal, or very visible.  If the terminal supports the visibility requested, return the
133   previous cursor state; otherwise raise an exception.  On many
134   terminals, the "visible" mode is an underline cursor and the "very visible" mode
135   is a block cursor.
136
137
138.. function:: def_prog_mode()
139
140   Save the current terminal mode as the "program" mode, the mode when the running
141   program is using curses.  (Its counterpart is the "shell" mode, for when the
142   program is not in curses.)  Subsequent calls to :func:`reset_prog_mode` will
143   restore this mode.
144
145
146.. function:: def_shell_mode()
147
148   Save the current terminal mode as the "shell" mode, the mode when the running
149   program is not using curses.  (Its counterpart is the "program" mode, when the
150   program is using curses capabilities.) Subsequent calls to
151   :func:`reset_shell_mode` will restore this mode.
152
153
154.. function:: delay_output(ms)
155
156   Insert an *ms* millisecond pause in output.
157
158
159.. function:: doupdate()
160
161   Update the physical screen.  The curses library keeps two data structures, one
162   representing the current physical screen contents and a virtual screen
163   representing the desired next state.  The :func:`doupdate` ground updates the
164   physical screen to match the virtual screen.
165
166   The virtual screen may be updated by a :meth:`~window.noutrefresh` call after write
167   operations such as :meth:`~window.addstr` have been performed on a window.  The normal
168   :meth:`~window.refresh` call is simply :meth:`!noutrefresh` followed by :func:`!doupdate`;
169   if you have to update multiple windows, you can speed performance and perhaps
170   reduce screen flicker by issuing :meth:`!noutrefresh` calls on all windows,
171   followed by a single :func:`!doupdate`.
172
173
174.. function:: echo()
175
176   Enter echo mode.  In echo mode, each character input is echoed to the screen as
177   it is entered.
178
179
180.. function:: endwin()
181
182   De-initialize the library, and return terminal to normal status.
183
184
185.. function:: erasechar()
186
187   Return the user's current erase character as a one-byte bytes object.  Under Unix operating systems this
188   is a property of the controlling tty of the curses program, and is not set by
189   the curses library itself.
190
191
192.. function:: filter()
193
194   The :func:`.filter` routine, if used, must be called before :func:`initscr` is
195   called.  The effect is that, during those calls, :envvar:`LINES` is set to ``1``; the
196   capabilities ``clear``, ``cup``, ``cud``, ``cud1``, ``cuu1``, ``cuu``, ``vpa`` are disabled; and the ``home``
197   string is set to the value of ``cr``. The effect is that the cursor is confined to
198   the current line, and so are screen updates.  This may be used for enabling
199   character-at-a-time  line editing without touching the rest of the screen.
200
201
202.. function:: flash()
203
204   Flash the screen.  That is, change it to reverse-video and then change it back
205   in a short interval.  Some people prefer such as 'visible bell' to the audible
206   attention signal produced by :func:`beep`.
207
208
209.. function:: flushinp()
210
211   Flush all input buffers.  This throws away any  typeahead  that  has been typed
212   by the user and has not yet been processed by the program.
213
214
215.. function:: getmouse()
216
217   After :meth:`~window.getch` returns :const:`KEY_MOUSE` to signal a mouse event, this
218   method should be called to retrieve the queued mouse event, represented as a
219   5-tuple ``(id, x, y, z, bstate)``. *id* is an ID value used to distinguish
220   multiple devices, and *x*, *y*, *z* are the event's coordinates.  (*z* is
221   currently unused.)  *bstate* is an integer value whose bits will be set to
222   indicate the type of event, and will be the bitwise OR of one or more of the
223   following constants, where *n* is the button number from 1 to 5:
224   :const:`BUTTONn_PRESSED`, :const:`BUTTONn_RELEASED`, :const:`BUTTONn_CLICKED`,
225   :const:`BUTTONn_DOUBLE_CLICKED`, :const:`BUTTONn_TRIPLE_CLICKED`,
226   :const:`BUTTON_SHIFT`, :const:`BUTTON_CTRL`, :const:`BUTTON_ALT`.
227
228   .. versionchanged:: 3.10
229      The ``BUTTON5_*`` constants are now exposed if they are provided by the
230      underlying curses library.
231
232
233.. function:: getsyx()
234
235   Return the current coordinates of the virtual screen cursor as a tuple
236   ``(y, x)``.  If :meth:`leaveok <window.leaveok>` is currently ``True``, then return ``(-1, -1)``.
237
238
239.. function:: getwin(file)
240
241   Read window related data stored in the file by an earlier :func:`putwin` call.
242   The routine then creates and initializes a new window using that data, returning
243   the new window object.
244
245
246.. function:: has_colors()
247
248   Return ``True`` if the terminal can display colors; otherwise, return ``False``.
249
250.. function:: has_extended_color_support()
251
252   Return ``True`` if the module supports extended colors; otherwise, return
253   ``False``. Extended color support allows more than 256 color pairs for
254   terminals that support more than 16 colors (e.g. xterm-256color).
255
256   Extended color support requires ncurses version 6.1 or later.
257
258   .. versionadded:: 3.10
259
260.. function:: has_ic()
261
262   Return ``True`` if the terminal has insert- and delete-character capabilities.
263   This function is included for historical reasons only, as all modern software
264   terminal emulators have such capabilities.
265
266
267.. function:: has_il()
268
269   Return ``True`` if the terminal has insert- and delete-line capabilities, or can
270   simulate  them  using scrolling regions. This function is included for
271   historical reasons only, as all modern software terminal emulators have such
272   capabilities.
273
274
275.. function:: has_key(ch)
276
277   Take a key value *ch*, and return ``True`` if the current terminal type recognizes
278   a key with that value.
279
280
281.. function:: halfdelay(tenths)
282
283   Used for half-delay mode, which is similar to cbreak mode in that characters
284   typed by the user are immediately available to the program. However, after
285   blocking for *tenths* tenths of seconds, raise an exception if nothing has
286   been typed.  The value of *tenths* must be a number between ``1`` and ``255``.  Use
287   :func:`nocbreak` to leave half-delay mode.
288
289
290.. function:: init_color(color_number, r, g, b)
291
292   Change the definition of a color, taking the number of the color to be changed
293   followed by three RGB values (for the amounts of red, green, and blue
294   components).  The value of *color_number* must be between ``0`` and
295   `COLORS - 1`.  Each of *r*, *g*, *b*, must be a value between ``0`` and
296   ``1000``.  When :func:`init_color` is used, all occurrences of that color on the
297   screen immediately change to the new definition.  This function is a no-op on
298   most terminals; it is active only if :func:`can_change_color` returns ``True``.
299
300
301.. function:: init_pair(pair_number, fg, bg)
302
303   Change the definition of a color-pair.  It takes three arguments: the number of
304   the color-pair to be changed, the foreground color number, and the background
305   color number.  The value of *pair_number* must be between ``1`` and
306   ``COLOR_PAIRS - 1`` (the ``0`` color pair is wired to white on black and cannot
307   be changed).  The value of *fg* and *bg* arguments must be between ``0`` and
308   ``COLORS - 1``, or, after calling :func:`use_default_colors`, ``-1``.
309   If the color-pair was previously initialized, the screen is
310   refreshed and all occurrences of that color-pair are changed to the new
311   definition.
312
313
314.. function:: initscr()
315
316   Initialize the library. Return a :ref:`window <curses-window-objects>` object
317   which represents the whole screen.
318
319   .. note::
320
321      If there is an error opening the terminal, the underlying curses library may
322      cause the interpreter to exit.
323
324
325.. function:: is_term_resized(nlines, ncols)
326
327   Return ``True`` if :func:`resize_term` would modify the window structure,
328   ``False`` otherwise.
329
330
331.. function:: isendwin()
332
333   Return ``True`` if :func:`endwin` has been called (that is, the  curses library has
334   been deinitialized).
335
336
337.. function:: keyname(k)
338
339   Return the name of the key numbered *k* as a bytes object.  The name of a key generating printable
340   ASCII character is the key's character.  The name of a control-key combination
341   is a two-byte bytes object consisting of a caret (``b'^'``) followed by the corresponding
342   printable ASCII character.  The name of an alt-key combination (128--255) is a
343   bytes object consisting of the prefix ``b'M-'`` followed by the name of the corresponding
344   ASCII character.
345
346
347.. function:: killchar()
348
349   Return the user's current line kill character as a one-byte bytes object. Under Unix operating systems
350   this is a property of the controlling tty of the curses program, and is not set
351   by the curses library itself.
352
353
354.. function:: longname()
355
356   Return a bytes object containing the terminfo long name field describing the current
357   terminal.  The maximum length of a verbose description is 128 characters.  It is
358   defined only after the call to :func:`initscr`.
359
360
361.. function:: meta(flag)
362
363   If *flag* is ``True``, allow 8-bit characters to be input.  If
364   *flag* is ``False``,  allow only 7-bit chars.
365
366
367.. function:: mouseinterval(interval)
368
369   Set the maximum time in milliseconds that can elapse between press and release
370   events in order for them to be recognized as a click, and return the previous
371   interval value.  The default value is 200 msec, or one fifth of a second.
372
373
374.. function:: mousemask(mousemask)
375
376   Set the mouse events to be reported, and return a tuple ``(availmask,
377   oldmask)``.   *availmask* indicates which of the specified mouse events can be
378   reported; on complete failure it returns ``0``.  *oldmask* is the previous value of
379   the given window's mouse event mask.  If this function is never called, no mouse
380   events are ever reported.
381
382
383.. function:: napms(ms)
384
385   Sleep for *ms* milliseconds.
386
387
388.. function:: newpad(nlines, ncols)
389
390   Create and return a pointer to a new pad data structure with the given number
391   of lines and columns.  Return a pad as a window object.
392
393   A pad is like a window, except that it is not restricted by the screen size, and
394   is not necessarily associated with a particular part of the screen.  Pads can be
395   used when a large window is needed, and only a part of the window will be on the
396   screen at one time.  Automatic refreshes of pads (such as from scrolling or
397   echoing of input) do not occur.  The :meth:`~window.refresh` and :meth:`~window.noutrefresh`
398   methods of a pad require 6 arguments to specify the part of the pad to be
399   displayed and the location on the screen to be used for the display. The
400   arguments are *pminrow*, *pmincol*, *sminrow*, *smincol*, *smaxrow*, *smaxcol*; the *p*
401   arguments refer to the upper left corner of the pad region to be displayed and
402   the *s* arguments define a clipping box on the screen within which the pad region
403   is to be displayed.
404
405
406.. function:: newwin(nlines, ncols)
407              newwin(nlines, ncols, begin_y, begin_x)
408
409   Return a new :ref:`window <curses-window-objects>`, whose left-upper corner
410   is at  ``(begin_y, begin_x)``, and whose height/width is  *nlines*/*ncols*.
411
412   By default, the window will extend from the  specified position to the lower
413   right corner of the screen.
414
415
416.. function:: nl()
417
418   Enter newline mode.  This mode translates the return key into newline on input,
419   and translates newline into return and line-feed on output. Newline mode is
420   initially on.
421
422
423.. function:: nocbreak()
424
425   Leave cbreak mode.  Return to normal "cooked" mode with line buffering.
426
427
428.. function:: noecho()
429
430   Leave echo mode.  Echoing of input characters is turned off.
431
432
433.. function:: nonl()
434
435   Leave newline mode.  Disable translation of return into newline on input, and
436   disable low-level translation of newline into newline/return on output (but this
437   does not change the behavior of ``addch('\n')``, which always does the
438   equivalent of return and line feed on the virtual screen).  With translation
439   off, curses can sometimes speed up vertical motion a little; also, it will be
440   able to detect the return key on input.
441
442
443.. function:: noqiflush()
444
445   When the :func:`!noqiflush` routine is used, normal flush of input and output queues
446   associated with the ``INTR``, ``QUIT`` and ``SUSP`` characters will not be done.  You may
447   want to call :func:`!noqiflush` in a signal handler if you want output to
448   continue as though the interrupt had not occurred, after the handler exits.
449
450
451.. function:: noraw()
452
453   Leave raw mode. Return to normal "cooked" mode with line buffering.
454
455
456.. function:: pair_content(pair_number)
457
458   Return a tuple ``(fg, bg)`` containing the colors for the requested color pair.
459   The value of *pair_number* must be between ``0`` and ``COLOR_PAIRS - 1``.
460
461
462.. function:: pair_number(attr)
463
464   Return the number of the color-pair set by the attribute value *attr*.
465   :func:`color_pair` is the counterpart to this function.
466
467
468.. function:: putp(str)
469
470   Equivalent to ``tputs(str, 1, putchar)``; emit the value of a specified
471   terminfo capability for the current terminal.  Note that the output of :func:`putp`
472   always goes to standard output.
473
474
475.. function:: qiflush([flag])
476
477   If *flag* is ``False``, the effect is the same as calling :func:`noqiflush`. If
478   *flag* is ``True``, or no argument is provided, the queues will be flushed when
479   these control characters are read.
480
481
482.. function:: raw()
483
484   Enter raw mode.  In raw mode, normal line buffering and  processing of
485   interrupt, quit, suspend, and flow control keys are turned off; characters are
486   presented to curses input functions one by one.
487
488
489.. function:: reset_prog_mode()
490
491   Restore the  terminal  to "program" mode, as previously saved  by
492   :func:`def_prog_mode`.
493
494
495.. function:: reset_shell_mode()
496
497   Restore the  terminal  to "shell" mode, as previously saved  by
498   :func:`def_shell_mode`.
499
500
501.. function:: resetty()
502
503   Restore the state of the terminal modes to what it was at the last call to
504   :func:`savetty`.
505
506
507.. function:: resize_term(nlines, ncols)
508
509   Backend function used by :func:`resizeterm`, performing most of the work;
510   when resizing the windows, :func:`resize_term` blank-fills the areas that are
511   extended.  The calling application should fill in these areas with
512   appropriate data.  The :func:`!resize_term` function attempts to resize all
513   windows.  However, due to the calling convention of pads, it is not possible
514   to resize these without additional interaction with the application.
515
516
517.. function:: resizeterm(nlines, ncols)
518
519   Resize the standard and current windows to the specified dimensions, and
520   adjusts other bookkeeping data used by the curses library that record the
521   window dimensions (in particular the SIGWINCH handler).
522
523
524.. function:: savetty()
525
526   Save the current state of the terminal modes in a buffer, usable by
527   :func:`resetty`.
528
529.. function:: get_escdelay()
530
531   Retrieves the value set by :func:`set_escdelay`.
532
533   .. versionadded:: 3.9
534
535.. function:: set_escdelay(ms)
536
537   Sets the number of milliseconds to wait after reading an escape character,
538   to distinguish between an individual escape character entered on the
539   keyboard from escape sequences sent by cursor and function keys.
540
541   .. versionadded:: 3.9
542
543.. function:: get_tabsize()
544
545   Retrieves the value set by :func:`set_tabsize`.
546
547   .. versionadded:: 3.9
548
549.. function:: set_tabsize(size)
550
551   Sets the number of columns used by the curses library when converting a tab
552   character to spaces as it adds the tab to a window.
553
554   .. versionadded:: 3.9
555
556.. function:: setsyx(y, x)
557
558   Set the virtual screen cursor to *y*, *x*. If *y* and *x* are both ``-1``, then
559   :meth:`leaveok <window.leaveok>` is set ``True``.
560
561
562.. function:: setupterm(term=None, fd=-1)
563
564   Initialize the terminal.  *term* is a string giving
565   the terminal name, or ``None``; if omitted or ``None``, the value of the
566   :envvar:`TERM` environment variable will be used.  *fd* is the
567   file descriptor to which any initialization sequences will be sent; if not
568   supplied or ``-1``, the file descriptor for ``sys.stdout`` will be used.
569
570
571.. function:: start_color()
572
573   Must be called if the programmer wants to use colors, and before any other color
574   manipulation routine is called.  It is good practice to call this routine right
575   after :func:`initscr`.
576
577   :func:`start_color` initializes eight basic colors (black, red,  green, yellow,
578   blue, magenta, cyan, and white), and two global variables in the :mod:`curses`
579   module, :const:`COLORS` and :const:`COLOR_PAIRS`, containing the maximum number
580   of colors and color-pairs the terminal can support.  It also restores the colors
581   on the terminal to the values they had when the terminal was just turned on.
582
583
584.. function:: termattrs()
585
586   Return a logical OR of all video attributes supported by the terminal.  This
587   information is useful when a curses program needs complete control over the
588   appearance of the screen.
589
590
591.. function:: termname()
592
593   Return the value of the environment variable :envvar:`TERM`, as a bytes object,
594   truncated to 14 characters.
595
596
597.. function:: tigetflag(capname)
598
599   Return the value of the Boolean capability corresponding to the terminfo
600   capability name *capname* as an integer.  Return the value ``-1`` if *capname* is not a
601   Boolean capability, or ``0`` if it is canceled or absent from the terminal
602   description.
603
604
605.. function:: tigetnum(capname)
606
607   Return the value of the numeric capability corresponding to the terminfo
608   capability name *capname* as an integer.  Return the value ``-2`` if *capname* is not a
609   numeric capability, or ``-1`` if it is canceled or absent from the terminal
610   description.
611
612
613.. function:: tigetstr(capname)
614
615   Return the value of the string capability corresponding to the terminfo
616   capability name *capname* as a bytes object.  Return ``None`` if *capname*
617   is not a terminfo "string capability", or is canceled or absent from the
618   terminal description.
619
620
621.. function:: tparm(str[, ...])
622
623   Instantiate the bytes object *str* with the supplied parameters, where *str* should
624   be a parameterized string obtained from the terminfo database.  E.g.
625   ``tparm(tigetstr("cup"), 5, 3)`` could result in ``b'\033[6;4H'``, the exact
626   result depending on terminal type.
627
628
629.. function:: typeahead(fd)
630
631   Specify that the file descriptor *fd* be used for typeahead checking.  If *fd*
632   is ``-1``, then no typeahead checking is done.
633
634   The curses library does "line-breakout optimization" by looking for typeahead
635   periodically while updating the screen.  If input is found, and it is coming
636   from a tty, the current update is postponed until refresh or doupdate is called
637   again, allowing faster response to commands typed in advance. This function
638   allows specifying a different file descriptor for typeahead checking.
639
640
641.. function:: unctrl(ch)
642
643   Return a bytes object which is a printable representation of the character *ch*.
644   Control characters are represented as a caret followed by the character, for
645   example as ``b'^C'``. Printing characters are left as they are.
646
647
648.. function:: ungetch(ch)
649
650   Push *ch* so the next :meth:`~window.getch` will return it.
651
652   .. note::
653
654      Only one *ch* can be pushed before :meth:`!getch` is called.
655
656
657.. function:: update_lines_cols()
658
659   Update :envvar:`LINES` and :envvar:`COLS`. Useful for detecting manual screen resize.
660
661   .. versionadded:: 3.5
662
663
664.. function:: unget_wch(ch)
665
666   Push *ch* so the next :meth:`~window.get_wch` will return it.
667
668   .. note::
669
670      Only one *ch* can be pushed before :meth:`!get_wch` is called.
671
672   .. versionadded:: 3.3
673
674
675.. function:: ungetmouse(id, x, y, z, bstate)
676
677   Push a :const:`KEY_MOUSE` event onto the input queue, associating the given
678   state data with it.
679
680
681.. function:: use_env(flag)
682
683   If used, this function should be called before :func:`initscr` or newterm are
684   called.  When *flag* is ``False``, the values of lines and columns specified in the
685   terminfo database will be used, even if environment variables :envvar:`LINES`
686   and :envvar:`COLUMNS` (used by default) are set, or if curses is running in a
687   window (in which case default behavior would be to use the window size if
688   :envvar:`LINES` and :envvar:`COLUMNS` are not set).
689
690
691.. function:: use_default_colors()
692
693   Allow use of default values for colors on terminals supporting this feature. Use
694   this to support transparency in your application.  The default color is assigned
695   to the color number ``-1``. After calling this function,  ``init_pair(x,
696   curses.COLOR_RED, -1)`` initializes, for instance, color pair *x* to a red
697   foreground color on the default background.
698
699
700.. function:: wrapper(func, /, *args, **kwargs)
701
702   Initialize curses and call another callable object, *func*, which should be the
703   rest of your curses-using application.  If the application raises an exception,
704   this function will restore the terminal to a sane state before re-raising the
705   exception and generating a traceback.  The callable object *func* is then passed
706   the main window 'stdscr' as its first argument, followed by any other arguments
707   passed to :func:`!wrapper`.  Before calling *func*, :func:`!wrapper` turns on
708   cbreak mode, turns off echo, enables the terminal keypad, and initializes colors
709   if the terminal has color support.  On exit (whether normally or by exception)
710   it restores cooked mode, turns on echo, and disables the terminal keypad.
711
712
713.. _curses-window-objects:
714
715Window Objects
716--------------
717
718Window objects, as returned by :func:`initscr` and :func:`newwin` above, have
719the following methods and attributes:
720
721
722.. method:: window.addch(ch[, attr])
723            window.addch(y, x, ch[, attr])
724
725   Paint character *ch* at ``(y, x)`` with attributes *attr*, overwriting any
726   character previously painted at that location.  By default, the character
727   position and attributes are the current settings for the window object.
728
729   .. note::
730
731      Writing outside the window, subwindow, or pad raises a :exc:`curses.error`.
732      Attempting to write to the lower right corner of a window, subwindow,
733      or pad will cause an exception to be raised after the character is printed.
734
735
736.. method:: window.addnstr(str, n[, attr])
737            window.addnstr(y, x, str, n[, attr])
738
739   Paint at most *n* characters of the character string *str* at
740   ``(y, x)`` with attributes
741   *attr*, overwriting anything previously on the display.
742
743
744.. method:: window.addstr(str[, attr])
745            window.addstr(y, x, str[, attr])
746
747   Paint the character string *str* at ``(y, x)`` with attributes
748   *attr*, overwriting anything previously on the display.
749
750   .. note::
751
752      * Writing outside the window, subwindow, or pad raises :exc:`curses.error`.
753        Attempting to write to the lower right corner of a window, subwindow,
754        or pad will cause an exception to be raised after the string is printed.
755
756      * A `bug in ncurses <https://bugs.python.org/issue35924>`_, the backend
757        for this Python module, can cause SegFaults when resizing windows. This
758        is fixed in ncurses-6.1-20190511.  If you are stuck with an earlier
759        ncurses, you can avoid triggering this if you do not call :func:`addstr`
760        with a *str* that has embedded newlines.  Instead, call :func:`addstr`
761        separately for each line.
762
763
764.. method:: window.attroff(attr)
765
766   Remove attribute *attr* from the "background" set applied to all writes to the
767   current window.
768
769
770.. method:: window.attron(attr)
771
772   Add attribute *attr* from the "background" set applied to all writes to the
773   current window.
774
775
776.. method:: window.attrset(attr)
777
778   Set the "background" set of attributes to *attr*.  This set is initially
779   ``0`` (no attributes).
780
781
782.. method:: window.bkgd(ch[, attr])
783
784   Set the background property of the window to the character *ch*, with
785   attributes *attr*.  The change is then applied to every character position in
786   that window:
787
788   * The attribute of every character in the window  is changed to the new
789     background attribute.
790
791   * Wherever  the  former background character appears, it is changed to the new
792     background character.
793
794
795.. method:: window.bkgdset(ch[, attr])
796
797   Set the window's background.  A window's background consists of a character and
798   any combination of attributes.  The attribute part of the background is combined
799   (OR'ed) with all non-blank characters that are written into the window.  Both
800   the character and attribute parts of the background are combined with the blank
801   characters.  The background becomes a property of the character and moves with
802   the character through any scrolling and insert/delete line/character operations.
803
804
805.. method:: window.border([ls[, rs[, ts[, bs[, tl[, tr[, bl[, br]]]]]]]])
806
807   Draw a border around the edges of the window. Each parameter specifies  the
808   character to use for a specific part of the border; see the table below for more
809   details.
810
811   .. note::
812
813      A ``0`` value for any parameter will cause the default character to be used for
814      that parameter.  Keyword parameters can *not* be used.  The defaults are listed
815      in this table:
816
817   +-----------+---------------------+-----------------------+
818   | Parameter | Description         | Default value         |
819   +===========+=====================+=======================+
820   | *ls*      | Left side           | :const:`ACS_VLINE`    |
821   +-----------+---------------------+-----------------------+
822   | *rs*      | Right side          | :const:`ACS_VLINE`    |
823   +-----------+---------------------+-----------------------+
824   | *ts*      | Top                 | :const:`ACS_HLINE`    |
825   +-----------+---------------------+-----------------------+
826   | *bs*      | Bottom              | :const:`ACS_HLINE`    |
827   +-----------+---------------------+-----------------------+
828   | *tl*      | Upper-left corner   | :const:`ACS_ULCORNER` |
829   +-----------+---------------------+-----------------------+
830   | *tr*      | Upper-right corner  | :const:`ACS_URCORNER` |
831   +-----------+---------------------+-----------------------+
832   | *bl*      | Bottom-left corner  | :const:`ACS_LLCORNER` |
833   +-----------+---------------------+-----------------------+
834   | *br*      | Bottom-right corner | :const:`ACS_LRCORNER` |
835   +-----------+---------------------+-----------------------+
836
837
838.. method:: window.box([vertch, horch])
839
840   Similar to :meth:`border`, but both *ls* and *rs* are *vertch* and both *ts* and
841   *bs* are *horch*.  The default corner characters are always used by this function.
842
843
844.. method:: window.chgat(attr)
845            window.chgat(num, attr)
846            window.chgat(y, x, attr)
847            window.chgat(y, x, num, attr)
848
849   Set the attributes of *num* characters at the current cursor position, or at
850   position ``(y, x)`` if supplied. If *num* is not given or is ``-1``,
851   the attribute will be set on all the characters to the end of the line.  This
852   function moves cursor to position ``(y, x)`` if supplied. The changed line
853   will be touched using the :meth:`touchline` method so that the contents will
854   be redisplayed by the next window refresh.
855
856
857.. method:: window.clear()
858
859   Like :meth:`erase`, but also cause the whole window to be repainted upon next
860   call to :meth:`refresh`.
861
862
863.. method:: window.clearok(flag)
864
865   If *flag* is ``True``, the next call to :meth:`refresh` will clear the window
866   completely.
867
868
869.. method:: window.clrtobot()
870
871   Erase from cursor to the end of the window: all lines below the cursor are
872   deleted, and then the equivalent of :meth:`clrtoeol` is performed.
873
874
875.. method:: window.clrtoeol()
876
877   Erase from cursor to the end of the line.
878
879
880.. method:: window.cursyncup()
881
882   Update the current cursor position of all the ancestors of the window to
883   reflect the current cursor position of the window.
884
885
886.. method:: window.delch([y, x])
887
888   Delete any character at ``(y, x)``.
889
890
891.. method:: window.deleteln()
892
893   Delete the line under the cursor. All following lines are moved up by one line.
894
895
896.. method:: window.derwin(begin_y, begin_x)
897            window.derwin(nlines, ncols, begin_y, begin_x)
898
899   An abbreviation for "derive window", :meth:`derwin` is the same as calling
900   :meth:`subwin`, except that *begin_y* and *begin_x* are relative to the origin
901   of the window, rather than relative to the entire screen.  Return a window
902   object for the derived window.
903
904
905.. method:: window.echochar(ch[, attr])
906
907   Add character *ch* with attribute *attr*, and immediately  call :meth:`refresh`
908   on the window.
909
910
911.. method:: window.enclose(y, x)
912
913   Test whether the given pair of screen-relative character-cell coordinates are
914   enclosed by the given window, returning ``True`` or ``False``.  It is useful for
915   determining what subset of the screen windows enclose the location of a mouse
916   event.
917
918   .. versionchanged:: 3.10
919      Previously it returned ``1`` or ``0`` instead of ``True`` or ``False``.
920
921
922.. attribute:: window.encoding
923
924   Encoding used to encode method arguments (Unicode strings and characters).
925   The encoding attribute is inherited from the parent window when a subwindow
926   is created, for example with :meth:`window.subwin`. By default, the locale
927   encoding is used (see :func:`locale.getpreferredencoding`).
928
929   .. versionadded:: 3.3
930
931
932.. method:: window.erase()
933
934   Clear the window.
935
936
937.. method:: window.getbegyx()
938
939   Return a tuple ``(y, x)`` of co-ordinates of upper-left corner.
940
941
942.. method:: window.getbkgd()
943
944   Return the given window's current background character/attribute pair.
945
946
947.. method:: window.getch([y, x])
948
949   Get a character. Note that the integer returned does *not* have to be in ASCII
950   range: function keys, keypad keys and so on are represented by numbers higher
951   than 255.  In no-delay mode, return ``-1`` if there is no input, otherwise
952   wait until a key is pressed.
953
954
955.. method:: window.get_wch([y, x])
956
957   Get a wide character. Return a character for most keys, or an integer for
958   function keys, keypad keys, and other special keys.
959   In no-delay mode, raise an exception if there is no input.
960
961   .. versionadded:: 3.3
962
963
964.. method:: window.getkey([y, x])
965
966   Get a character, returning a string instead of an integer, as :meth:`getch`
967   does. Function keys, keypad keys and other special keys return a multibyte
968   string containing the key name.  In no-delay mode, raise an exception if
969   there is no input.
970
971
972.. method:: window.getmaxyx()
973
974   Return a tuple ``(y, x)`` of the height and width of the window.
975
976
977.. method:: window.getparyx()
978
979   Return the beginning coordinates of this window relative to its parent window
980   as a tuple ``(y, x)``.  Return ``(-1, -1)`` if this window has no
981   parent.
982
983
984.. method:: window.getstr()
985            window.getstr(n)
986            window.getstr(y, x)
987            window.getstr(y, x, n)
988
989   Read a bytes object from the user, with primitive line editing capacity.
990
991
992.. method:: window.getyx()
993
994   Return a tuple ``(y, x)`` of current cursor position  relative to the window's
995   upper-left corner.
996
997
998.. method:: window.hline(ch, n)
999            window.hline(y, x, ch, n)
1000
1001   Display a horizontal line starting at ``(y, x)`` with length *n* consisting of
1002   the character *ch*.
1003
1004
1005.. method:: window.idcok(flag)
1006
1007   If *flag* is ``False``, curses no longer considers using the hardware insert/delete
1008   character feature of the terminal; if *flag* is ``True``, use of character insertion
1009   and deletion is enabled.  When curses is first initialized, use of character
1010   insert/delete is enabled by default.
1011
1012
1013.. method:: window.idlok(flag)
1014
1015   If *flag* is ``True``, :mod:`curses` will try and use hardware line
1016   editing facilities. Otherwise, line insertion/deletion are disabled.
1017
1018
1019.. method:: window.immedok(flag)
1020
1021   If *flag* is ``True``, any change in the window image automatically causes the
1022   window to be refreshed; you no longer have to call :meth:`refresh` yourself.
1023   However, it may degrade performance considerably, due to repeated calls to
1024   wrefresh.  This option is disabled by default.
1025
1026
1027.. method:: window.inch([y, x])
1028
1029   Return the character at the given position in the window. The bottom 8 bits are
1030   the character proper, and upper bits are the attributes.
1031
1032
1033.. method:: window.insch(ch[, attr])
1034            window.insch(y, x, ch[, attr])
1035
1036   Paint character *ch* at ``(y, x)`` with attributes *attr*, moving the line from
1037   position *x* right by one character.
1038
1039
1040.. method:: window.insdelln(nlines)
1041
1042   Insert *nlines* lines into the specified window above the current line.  The
1043   *nlines* bottom lines are lost.  For negative *nlines*, delete *nlines* lines
1044   starting with the one under the cursor, and move the remaining lines up.  The
1045   bottom *nlines* lines are cleared.  The current cursor position remains the
1046   same.
1047
1048
1049.. method:: window.insertln()
1050
1051   Insert a blank line under the cursor. All following lines are moved down by one
1052   line.
1053
1054
1055.. method:: window.insnstr(str, n[, attr])
1056            window.insnstr(y, x, str, n[, attr])
1057
1058   Insert a character string (as many characters as will fit on the line) before
1059   the character under the cursor, up to *n* characters.   If *n* is zero or
1060   negative, the entire string is inserted. All characters to the right of the
1061   cursor are shifted right, with the rightmost characters on the line being lost.
1062   The cursor position does not change (after moving to *y*, *x*, if specified).
1063
1064
1065.. method:: window.insstr(str[, attr])
1066            window.insstr(y, x, str[, attr])
1067
1068   Insert a character string (as many characters as will fit on the line) before
1069   the character under the cursor.  All characters to the right of the cursor are
1070   shifted right, with the rightmost characters on the line being lost.  The cursor
1071   position does not change (after moving to *y*, *x*, if specified).
1072
1073
1074.. method:: window.instr([n])
1075            window.instr(y, x[, n])
1076
1077   Return a bytes object of characters, extracted from the window starting at the
1078   current cursor position, or at *y*, *x* if specified. Attributes are stripped
1079   from the characters.  If *n* is specified, :meth:`instr` returns a string
1080   at most *n* characters long (exclusive of the trailing NUL).
1081
1082
1083.. method:: window.is_linetouched(line)
1084
1085   Return ``True`` if the specified line was modified since the last call to
1086   :meth:`refresh`; otherwise return ``False``.  Raise a :exc:`curses.error`
1087   exception if *line* is not valid for the given window.
1088
1089
1090.. method:: window.is_wintouched()
1091
1092   Return ``True`` if the specified window was modified since the last call to
1093   :meth:`refresh`; otherwise return ``False``.
1094
1095
1096.. method:: window.keypad(flag)
1097
1098   If *flag* is ``True``, escape sequences generated by some keys (keypad,  function keys)
1099   will be interpreted by :mod:`curses`. If *flag* is ``False``, escape sequences will be
1100   left as is in the input stream.
1101
1102
1103.. method:: window.leaveok(flag)
1104
1105   If *flag* is ``True``, cursor is left where it is on update, instead of being at "cursor
1106   position."  This reduces cursor movement where possible. If possible the cursor
1107   will be made invisible.
1108
1109   If *flag* is ``False``, cursor will always be at "cursor position" after an update.
1110
1111
1112.. method:: window.move(new_y, new_x)
1113
1114   Move cursor to ``(new_y, new_x)``.
1115
1116
1117.. method:: window.mvderwin(y, x)
1118
1119   Move the window inside its parent window.  The screen-relative parameters of
1120   the window are not changed.  This routine is used to display different parts of
1121   the parent window at the same physical position on the screen.
1122
1123
1124.. method:: window.mvwin(new_y, new_x)
1125
1126   Move the window so its upper-left corner is at ``(new_y, new_x)``.
1127
1128
1129.. method:: window.nodelay(flag)
1130
1131   If *flag* is ``True``, :meth:`getch` will be non-blocking.
1132
1133
1134.. method:: window.notimeout(flag)
1135
1136   If *flag* is ``True``, escape sequences will not be timed out.
1137
1138   If *flag* is ``False``, after a few milliseconds, an escape sequence will not be
1139   interpreted, and will be left in the input stream as is.
1140
1141
1142.. method:: window.noutrefresh()
1143
1144   Mark for refresh but wait.  This function updates the data structure
1145   representing the desired state of the window, but does not force an update of
1146   the physical screen.  To accomplish that, call  :func:`doupdate`.
1147
1148
1149.. method:: window.overlay(destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol])
1150
1151   Overlay the window on top of *destwin*. The windows need not be the same size,
1152   only the overlapping region is copied. This copy is non-destructive, which means
1153   that the current background character does not overwrite the old contents of
1154   *destwin*.
1155
1156   To get fine-grained control over the copied region, the second form of
1157   :meth:`overlay` can be used. *sminrow* and *smincol* are the upper-left
1158   coordinates of the source window, and the other variables mark a rectangle in
1159   the destination window.
1160
1161
1162.. method:: window.overwrite(destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol])
1163
1164   Overwrite the window on top of *destwin*. The windows need not be the same size,
1165   in which case only the overlapping region is copied. This copy is destructive,
1166   which means that the current background character overwrites the old contents of
1167   *destwin*.
1168
1169   To get fine-grained control over the copied region, the second form of
1170   :meth:`overwrite` can be used. *sminrow* and *smincol* are the upper-left
1171   coordinates of the source window, the other variables mark a rectangle in the
1172   destination window.
1173
1174
1175.. method:: window.putwin(file)
1176
1177   Write all data associated with the window into the provided file object.  This
1178   information can be later retrieved using the :func:`getwin` function.
1179
1180
1181.. method:: window.redrawln(beg, num)
1182
1183   Indicate that the *num* screen lines, starting at line *beg*, are corrupted and
1184   should be completely redrawn on the next :meth:`refresh` call.
1185
1186
1187.. method:: window.redrawwin()
1188
1189   Touch the entire window, causing it to be completely redrawn on the next
1190   :meth:`refresh` call.
1191
1192
1193.. method:: window.refresh([pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol])
1194
1195   Update the display immediately (sync actual screen with previous
1196   drawing/deleting methods).
1197
1198   The 6 optional arguments can only be specified when the window is a pad created
1199   with :func:`newpad`.  The additional parameters are needed to indicate what part
1200   of the pad and screen are involved. *pminrow* and *pmincol* specify the upper
1201   left-hand corner of the rectangle to be displayed in the pad.  *sminrow*,
1202   *smincol*, *smaxrow*, and *smaxcol* specify the edges of the rectangle to be
1203   displayed on the screen.  The lower right-hand corner of the rectangle to be
1204   displayed in the pad is calculated from the screen coordinates, since the
1205   rectangles must be the same size.  Both rectangles must be entirely contained
1206   within their respective structures.  Negative values of *pminrow*, *pmincol*,
1207   *sminrow*, or *smincol* are treated as if they were zero.
1208
1209
1210.. method:: window.resize(nlines, ncols)
1211
1212   Reallocate storage for a curses window to adjust its dimensions to the
1213   specified values.  If either dimension is larger than the current values, the
1214   window's data is filled with blanks that have the current background
1215   rendition (as set by :meth:`bkgdset`) merged into them.
1216
1217
1218.. method:: window.scroll([lines=1])
1219
1220   Scroll the screen or scrolling region upward by *lines* lines.
1221
1222
1223.. method:: window.scrollok(flag)
1224
1225   Control what happens when the cursor of a window is moved off the edge of the
1226   window or scrolling region, either as a result of a newline action on the bottom
1227   line, or typing the last character of the last line.  If *flag* is ``False``, the
1228   cursor is left on the bottom line.  If *flag* is ``True``, the window is scrolled up
1229   one line.  Note that in order to get the physical scrolling effect on the
1230   terminal, it is also necessary to call :meth:`idlok`.
1231
1232
1233.. method:: window.setscrreg(top, bottom)
1234
1235   Set the scrolling region from line *top* to line *bottom*. All scrolling actions
1236   will take place in this region.
1237
1238
1239.. method:: window.standend()
1240
1241   Turn off the standout attribute.  On some terminals this has the side effect of
1242   turning off all attributes.
1243
1244
1245.. method:: window.standout()
1246
1247   Turn on attribute *A_STANDOUT*.
1248
1249
1250.. method:: window.subpad(begin_y, begin_x)
1251            window.subpad(nlines, ncols, begin_y, begin_x)
1252
1253   Return a sub-window, whose upper-left corner is at ``(begin_y, begin_x)``, and
1254   whose width/height is *ncols*/*nlines*.
1255
1256
1257.. method:: window.subwin(begin_y, begin_x)
1258            window.subwin(nlines, ncols, begin_y, begin_x)
1259
1260   Return a sub-window, whose upper-left corner is at ``(begin_y, begin_x)``, and
1261   whose width/height is *ncols*/*nlines*.
1262
1263   By default, the sub-window will extend from the specified position to the lower
1264   right corner of the window.
1265
1266
1267.. method:: window.syncdown()
1268
1269   Touch each location in the window that has been touched in any of its ancestor
1270   windows.  This routine is called by :meth:`refresh`, so it should almost never
1271   be necessary to call it manually.
1272
1273
1274.. method:: window.syncok(flag)
1275
1276   If *flag* is ``True``, then :meth:`syncup` is called automatically
1277   whenever there is a change in the window.
1278
1279
1280.. method:: window.syncup()
1281
1282   Touch all locations in ancestors of the window that have been changed in  the
1283   window.
1284
1285
1286.. method:: window.timeout(delay)
1287
1288   Set blocking or non-blocking read behavior for the window.  If *delay* is
1289   negative, blocking read is used (which will wait indefinitely for input).  If
1290   *delay* is zero, then non-blocking read is used, and :meth:`getch` will
1291   return ``-1`` if no input is waiting.  If *delay* is positive, then
1292   :meth:`getch` will block for *delay* milliseconds, and return ``-1`` if there is
1293   still no input at the end of that time.
1294
1295
1296.. method:: window.touchline(start, count[, changed])
1297
1298   Pretend *count* lines have been changed, starting with line *start*.  If
1299   *changed* is supplied, it specifies whether the affected lines are marked as
1300   having been changed (*changed*\ ``=True``) or unchanged (*changed*\ ``=False``).
1301
1302
1303.. method:: window.touchwin()
1304
1305   Pretend the whole window has been changed, for purposes of drawing
1306   optimizations.
1307
1308
1309.. method:: window.untouchwin()
1310
1311   Mark all lines in  the  window  as unchanged since the last call to
1312   :meth:`refresh`.
1313
1314
1315.. method:: window.vline(ch, n)
1316            window.vline(y, x, ch, n)
1317
1318   Display a vertical line starting at ``(y, x)`` with length *n* consisting of the
1319   character *ch*.
1320
1321
1322Constants
1323---------
1324
1325The :mod:`curses` module defines the following data members:
1326
1327
1328.. data:: ERR
1329
1330   Some curses routines  that  return  an integer, such as :meth:`~window.getch`, return
1331   :const:`ERR` upon failure.
1332
1333
1334.. data:: OK
1335
1336   Some curses routines  that  return  an integer, such as  :func:`napms`, return
1337   :const:`OK` upon success.
1338
1339
1340.. data:: version
1341
1342   A bytes object representing the current version of the module.  Also available as
1343   :const:`__version__`.
1344
1345
1346.. data:: ncurses_version
1347
1348   A named tuple containing the three components of the ncurses library
1349   version: *major*, *minor*, and *patch*.  All values are integers.  The
1350   components can also be accessed by name,  so ``curses.ncurses_version[0]``
1351   is equivalent to ``curses.ncurses_version.major`` and so on.
1352
1353   Availability: if the ncurses library is used.
1354
1355   .. versionadded:: 3.8
1356
1357
1358Some constants are available to specify character cell attributes.
1359The exact constants available are system dependent.
1360
1361+------------------+-------------------------------+
1362| Attribute        | Meaning                       |
1363+==================+===============================+
1364| ``A_ALTCHARSET`` | Alternate character set mode  |
1365+------------------+-------------------------------+
1366| ``A_BLINK``      | Blink mode                    |
1367+------------------+-------------------------------+
1368| ``A_BOLD``       | Bold mode                     |
1369+------------------+-------------------------------+
1370| ``A_DIM``        | Dim mode                      |
1371+------------------+-------------------------------+
1372| ``A_INVIS``      | Invisible or blank mode       |
1373+------------------+-------------------------------+
1374| ``A_ITALIC``     | Italic mode                   |
1375+------------------+-------------------------------+
1376| ``A_NORMAL``     | Normal attribute              |
1377+------------------+-------------------------------+
1378| ``A_PROTECT``    | Protected mode                |
1379+------------------+-------------------------------+
1380| ``A_REVERSE``    | Reverse background and        |
1381|                  | foreground colors             |
1382+------------------+-------------------------------+
1383| ``A_STANDOUT``   | Standout mode                 |
1384+------------------+-------------------------------+
1385| ``A_UNDERLINE``  | Underline mode                |
1386+------------------+-------------------------------+
1387| ``A_HORIZONTAL`` | Horizontal highlight          |
1388+------------------+-------------------------------+
1389| ``A_LEFT``       | Left highlight                |
1390+------------------+-------------------------------+
1391| ``A_LOW``        | Low highlight                 |
1392+------------------+-------------------------------+
1393| ``A_RIGHT``      | Right highlight               |
1394+------------------+-------------------------------+
1395| ``A_TOP``        | Top highlight                 |
1396+------------------+-------------------------------+
1397| ``A_VERTICAL``   | Vertical highlight            |
1398+------------------+-------------------------------+
1399| ``A_CHARTEXT``   | Bit-mask to extract a         |
1400|                  | character                     |
1401+------------------+-------------------------------+
1402
1403.. versionadded:: 3.7
1404   ``A_ITALIC`` was added.
1405
1406Several constants are available to extract corresponding attributes returned
1407by some methods.
1408
1409+------------------+-------------------------------+
1410| Bit-mask         | Meaning                       |
1411+==================+===============================+
1412| ``A_ATTRIBUTES`` | Bit-mask to extract           |
1413|                  | attributes                    |
1414+------------------+-------------------------------+
1415| ``A_CHARTEXT``   | Bit-mask to extract a         |
1416|                  | character                     |
1417+------------------+-------------------------------+
1418| ``A_COLOR``      | Bit-mask to extract           |
1419|                  | color-pair field information  |
1420+------------------+-------------------------------+
1421
1422Keys are referred to by integer constants with names starting with  ``KEY_``.
1423The exact keycaps available are system dependent.
1424
1425.. XXX this table is far too large! should it be alphabetized?
1426
1427+-------------------+--------------------------------------------+
1428| Key constant      | Key                                        |
1429+===================+============================================+
1430| ``KEY_MIN``       | Minimum key value                          |
1431+-------------------+--------------------------------------------+
1432| ``KEY_BREAK``     | Break key (unreliable)                     |
1433+-------------------+--------------------------------------------+
1434| ``KEY_DOWN``      | Down-arrow                                 |
1435+-------------------+--------------------------------------------+
1436| ``KEY_UP``        | Up-arrow                                   |
1437+-------------------+--------------------------------------------+
1438| ``KEY_LEFT``      | Left-arrow                                 |
1439+-------------------+--------------------------------------------+
1440| ``KEY_RIGHT``     | Right-arrow                                |
1441+-------------------+--------------------------------------------+
1442| ``KEY_HOME``      | Home key (upward+left arrow)               |
1443+-------------------+--------------------------------------------+
1444| ``KEY_BACKSPACE`` | Backspace (unreliable)                     |
1445+-------------------+--------------------------------------------+
1446| ``KEY_F0``        | Function keys.  Up to 64 function keys are |
1447|                   | supported.                                 |
1448+-------------------+--------------------------------------------+
1449| ``KEY_Fn``        | Value of function key *n*                  |
1450+-------------------+--------------------------------------------+
1451| ``KEY_DL``        | Delete line                                |
1452+-------------------+--------------------------------------------+
1453| ``KEY_IL``        | Insert line                                |
1454+-------------------+--------------------------------------------+
1455| ``KEY_DC``        | Delete character                           |
1456+-------------------+--------------------------------------------+
1457| ``KEY_IC``        | Insert char or enter insert mode           |
1458+-------------------+--------------------------------------------+
1459| ``KEY_EIC``       | Exit insert char mode                      |
1460+-------------------+--------------------------------------------+
1461| ``KEY_CLEAR``     | Clear screen                               |
1462+-------------------+--------------------------------------------+
1463| ``KEY_EOS``       | Clear to end of screen                     |
1464+-------------------+--------------------------------------------+
1465| ``KEY_EOL``       | Clear to end of line                       |
1466+-------------------+--------------------------------------------+
1467| ``KEY_SF``        | Scroll 1 line forward                      |
1468+-------------------+--------------------------------------------+
1469| ``KEY_SR``        | Scroll 1 line backward (reverse)           |
1470+-------------------+--------------------------------------------+
1471| ``KEY_NPAGE``     | Next page                                  |
1472+-------------------+--------------------------------------------+
1473| ``KEY_PPAGE``     | Previous page                              |
1474+-------------------+--------------------------------------------+
1475| ``KEY_STAB``      | Set tab                                    |
1476+-------------------+--------------------------------------------+
1477| ``KEY_CTAB``      | Clear tab                                  |
1478+-------------------+--------------------------------------------+
1479| ``KEY_CATAB``     | Clear all tabs                             |
1480+-------------------+--------------------------------------------+
1481| ``KEY_ENTER``     | Enter or send (unreliable)                 |
1482+-------------------+--------------------------------------------+
1483| ``KEY_SRESET``    | Soft (partial) reset (unreliable)          |
1484+-------------------+--------------------------------------------+
1485| ``KEY_RESET``     | Reset or hard reset (unreliable)           |
1486+-------------------+--------------------------------------------+
1487| ``KEY_PRINT``     | Print                                      |
1488+-------------------+--------------------------------------------+
1489| ``KEY_LL``        | Home down or bottom (lower left)           |
1490+-------------------+--------------------------------------------+
1491| ``KEY_A1``        | Upper left of keypad                       |
1492+-------------------+--------------------------------------------+
1493| ``KEY_A3``        | Upper right of keypad                      |
1494+-------------------+--------------------------------------------+
1495| ``KEY_B2``        | Center of keypad                           |
1496+-------------------+--------------------------------------------+
1497| ``KEY_C1``        | Lower left of keypad                       |
1498+-------------------+--------------------------------------------+
1499| ``KEY_C3``        | Lower right of keypad                      |
1500+-------------------+--------------------------------------------+
1501| ``KEY_BTAB``      | Back tab                                   |
1502+-------------------+--------------------------------------------+
1503| ``KEY_BEG``       | Beg (beginning)                            |
1504+-------------------+--------------------------------------------+
1505| ``KEY_CANCEL``    | Cancel                                     |
1506+-------------------+--------------------------------------------+
1507| ``KEY_CLOSE``     | Close                                      |
1508+-------------------+--------------------------------------------+
1509| ``KEY_COMMAND``   | Cmd (command)                              |
1510+-------------------+--------------------------------------------+
1511| ``KEY_COPY``      | Copy                                       |
1512+-------------------+--------------------------------------------+
1513| ``KEY_CREATE``    | Create                                     |
1514+-------------------+--------------------------------------------+
1515| ``KEY_END``       | End                                        |
1516+-------------------+--------------------------------------------+
1517| ``KEY_EXIT``      | Exit                                       |
1518+-------------------+--------------------------------------------+
1519| ``KEY_FIND``      | Find                                       |
1520+-------------------+--------------------------------------------+
1521| ``KEY_HELP``      | Help                                       |
1522+-------------------+--------------------------------------------+
1523| ``KEY_MARK``      | Mark                                       |
1524+-------------------+--------------------------------------------+
1525| ``KEY_MESSAGE``   | Message                                    |
1526+-------------------+--------------------------------------------+
1527| ``KEY_MOVE``      | Move                                       |
1528+-------------------+--------------------------------------------+
1529| ``KEY_NEXT``      | Next                                       |
1530+-------------------+--------------------------------------------+
1531| ``KEY_OPEN``      | Open                                       |
1532+-------------------+--------------------------------------------+
1533| ``KEY_OPTIONS``   | Options                                    |
1534+-------------------+--------------------------------------------+
1535| ``KEY_PREVIOUS``  | Prev (previous)                            |
1536+-------------------+--------------------------------------------+
1537| ``KEY_REDO``      | Redo                                       |
1538+-------------------+--------------------------------------------+
1539| ``KEY_REFERENCE`` | Ref (reference)                            |
1540+-------------------+--------------------------------------------+
1541| ``KEY_REFRESH``   | Refresh                                    |
1542+-------------------+--------------------------------------------+
1543| ``KEY_REPLACE``   | Replace                                    |
1544+-------------------+--------------------------------------------+
1545| ``KEY_RESTART``   | Restart                                    |
1546+-------------------+--------------------------------------------+
1547| ``KEY_RESUME``    | Resume                                     |
1548+-------------------+--------------------------------------------+
1549| ``KEY_SAVE``      | Save                                       |
1550+-------------------+--------------------------------------------+
1551| ``KEY_SBEG``      | Shifted Beg (beginning)                    |
1552+-------------------+--------------------------------------------+
1553| ``KEY_SCANCEL``   | Shifted Cancel                             |
1554+-------------------+--------------------------------------------+
1555| ``KEY_SCOMMAND``  | Shifted Command                            |
1556+-------------------+--------------------------------------------+
1557| ``KEY_SCOPY``     | Shifted Copy                               |
1558+-------------------+--------------------------------------------+
1559| ``KEY_SCREATE``   | Shifted Create                             |
1560+-------------------+--------------------------------------------+
1561| ``KEY_SDC``       | Shifted Delete char                        |
1562+-------------------+--------------------------------------------+
1563| ``KEY_SDL``       | Shifted Delete line                        |
1564+-------------------+--------------------------------------------+
1565| ``KEY_SELECT``    | Select                                     |
1566+-------------------+--------------------------------------------+
1567| ``KEY_SEND``      | Shifted End                                |
1568+-------------------+--------------------------------------------+
1569| ``KEY_SEOL``      | Shifted Clear line                         |
1570+-------------------+--------------------------------------------+
1571| ``KEY_SEXIT``     | Shifted Exit                               |
1572+-------------------+--------------------------------------------+
1573| ``KEY_SFIND``     | Shifted Find                               |
1574+-------------------+--------------------------------------------+
1575| ``KEY_SHELP``     | Shifted Help                               |
1576+-------------------+--------------------------------------------+
1577| ``KEY_SHOME``     | Shifted Home                               |
1578+-------------------+--------------------------------------------+
1579| ``KEY_SIC``       | Shifted Input                              |
1580+-------------------+--------------------------------------------+
1581| ``KEY_SLEFT``     | Shifted Left arrow                         |
1582+-------------------+--------------------------------------------+
1583| ``KEY_SMESSAGE``  | Shifted Message                            |
1584+-------------------+--------------------------------------------+
1585| ``KEY_SMOVE``     | Shifted Move                               |
1586+-------------------+--------------------------------------------+
1587| ``KEY_SNEXT``     | Shifted Next                               |
1588+-------------------+--------------------------------------------+
1589| ``KEY_SOPTIONS``  | Shifted Options                            |
1590+-------------------+--------------------------------------------+
1591| ``KEY_SPREVIOUS`` | Shifted Prev                               |
1592+-------------------+--------------------------------------------+
1593| ``KEY_SPRINT``    | Shifted Print                              |
1594+-------------------+--------------------------------------------+
1595| ``KEY_SREDO``     | Shifted Redo                               |
1596+-------------------+--------------------------------------------+
1597| ``KEY_SREPLACE``  | Shifted Replace                            |
1598+-------------------+--------------------------------------------+
1599| ``KEY_SRIGHT``    | Shifted Right arrow                        |
1600+-------------------+--------------------------------------------+
1601| ``KEY_SRSUME``    | Shifted Resume                             |
1602+-------------------+--------------------------------------------+
1603| ``KEY_SSAVE``     | Shifted Save                               |
1604+-------------------+--------------------------------------------+
1605| ``KEY_SSUSPEND``  | Shifted Suspend                            |
1606+-------------------+--------------------------------------------+
1607| ``KEY_SUNDO``     | Shifted Undo                               |
1608+-------------------+--------------------------------------------+
1609| ``KEY_SUSPEND``   | Suspend                                    |
1610+-------------------+--------------------------------------------+
1611| ``KEY_UNDO``      | Undo                                       |
1612+-------------------+--------------------------------------------+
1613| ``KEY_MOUSE``     | Mouse event has occurred                   |
1614+-------------------+--------------------------------------------+
1615| ``KEY_RESIZE``    | Terminal resize event                      |
1616+-------------------+--------------------------------------------+
1617| ``KEY_MAX``       | Maximum key value                          |
1618+-------------------+--------------------------------------------+
1619
1620On VT100s and their software emulations, such as X terminal emulators, there are
1621normally at least four function keys (:const:`KEY_F1`, :const:`KEY_F2`,
1622:const:`KEY_F3`, :const:`KEY_F4`) available, and the arrow keys mapped to
1623:const:`KEY_UP`, :const:`KEY_DOWN`, :const:`KEY_LEFT` and :const:`KEY_RIGHT` in
1624the obvious way.  If your machine has a PC keyboard, it is safe to expect arrow
1625keys and twelve function keys (older PC keyboards may have only ten function
1626keys); also, the following keypad mappings are standard:
1627
1628+------------------+-----------+
1629| Keycap           | Constant  |
1630+==================+===========+
1631| :kbd:`Insert`    | KEY_IC    |
1632+------------------+-----------+
1633| :kbd:`Delete`    | KEY_DC    |
1634+------------------+-----------+
1635| :kbd:`Home`      | KEY_HOME  |
1636+------------------+-----------+
1637| :kbd:`End`       | KEY_END   |
1638+------------------+-----------+
1639| :kbd:`Page Up`   | KEY_PPAGE |
1640+------------------+-----------+
1641| :kbd:`Page Down` | KEY_NPAGE |
1642+------------------+-----------+
1643
1644The following table lists characters from the alternate character set. These are
1645inherited from the VT100 terminal, and will generally be  available on software
1646emulations such as X terminals.  When there is no graphic available, curses
1647falls back on a crude printable ASCII approximation.
1648
1649.. note::
1650
1651   These are available only after :func:`initscr` has  been called.
1652
1653+------------------+------------------------------------------+
1654| ACS code         | Meaning                                  |
1655+==================+==========================================+
1656| ``ACS_BBSS``     | alternate name for upper right corner    |
1657+------------------+------------------------------------------+
1658| ``ACS_BLOCK``    | solid square block                       |
1659+------------------+------------------------------------------+
1660| ``ACS_BOARD``    | board of squares                         |
1661+------------------+------------------------------------------+
1662| ``ACS_BSBS``     | alternate name for horizontal line       |
1663+------------------+------------------------------------------+
1664| ``ACS_BSSB``     | alternate name for upper left corner     |
1665+------------------+------------------------------------------+
1666| ``ACS_BSSS``     | alternate name for top tee               |
1667+------------------+------------------------------------------+
1668| ``ACS_BTEE``     | bottom tee                               |
1669+------------------+------------------------------------------+
1670| ``ACS_BULLET``   | bullet                                   |
1671+------------------+------------------------------------------+
1672| ``ACS_CKBOARD``  | checker board (stipple)                  |
1673+------------------+------------------------------------------+
1674| ``ACS_DARROW``   | arrow pointing down                      |
1675+------------------+------------------------------------------+
1676| ``ACS_DEGREE``   | degree symbol                            |
1677+------------------+------------------------------------------+
1678| ``ACS_DIAMOND``  | diamond                                  |
1679+------------------+------------------------------------------+
1680| ``ACS_GEQUAL``   | greater-than-or-equal-to                 |
1681+------------------+------------------------------------------+
1682| ``ACS_HLINE``    | horizontal line                          |
1683+------------------+------------------------------------------+
1684| ``ACS_LANTERN``  | lantern symbol                           |
1685+------------------+------------------------------------------+
1686| ``ACS_LARROW``   | left arrow                               |
1687+------------------+------------------------------------------+
1688| ``ACS_LEQUAL``   | less-than-or-equal-to                    |
1689+------------------+------------------------------------------+
1690| ``ACS_LLCORNER`` | lower left-hand corner                   |
1691+------------------+------------------------------------------+
1692| ``ACS_LRCORNER`` | lower right-hand corner                  |
1693+------------------+------------------------------------------+
1694| ``ACS_LTEE``     | left tee                                 |
1695+------------------+------------------------------------------+
1696| ``ACS_NEQUAL``   | not-equal sign                           |
1697+------------------+------------------------------------------+
1698| ``ACS_PI``       | letter pi                                |
1699+------------------+------------------------------------------+
1700| ``ACS_PLMINUS``  | plus-or-minus sign                       |
1701+------------------+------------------------------------------+
1702| ``ACS_PLUS``     | big plus sign                            |
1703+------------------+------------------------------------------+
1704| ``ACS_RARROW``   | right arrow                              |
1705+------------------+------------------------------------------+
1706| ``ACS_RTEE``     | right tee                                |
1707+------------------+------------------------------------------+
1708| ``ACS_S1``       | scan line 1                              |
1709+------------------+------------------------------------------+
1710| ``ACS_S3``       | scan line 3                              |
1711+------------------+------------------------------------------+
1712| ``ACS_S7``       | scan line 7                              |
1713+------------------+------------------------------------------+
1714| ``ACS_S9``       | scan line 9                              |
1715+------------------+------------------------------------------+
1716| ``ACS_SBBS``     | alternate name for lower right corner    |
1717+------------------+------------------------------------------+
1718| ``ACS_SBSB``     | alternate name for vertical line         |
1719+------------------+------------------------------------------+
1720| ``ACS_SBSS``     | alternate name for right tee             |
1721+------------------+------------------------------------------+
1722| ``ACS_SSBB``     | alternate name for lower left corner     |
1723+------------------+------------------------------------------+
1724| ``ACS_SSBS``     | alternate name for bottom tee            |
1725+------------------+------------------------------------------+
1726| ``ACS_SSSB``     | alternate name for left tee              |
1727+------------------+------------------------------------------+
1728| ``ACS_SSSS``     | alternate name for crossover or big plus |
1729+------------------+------------------------------------------+
1730| ``ACS_STERLING`` | pound sterling                           |
1731+------------------+------------------------------------------+
1732| ``ACS_TTEE``     | top tee                                  |
1733+------------------+------------------------------------------+
1734| ``ACS_UARROW``   | up arrow                                 |
1735+------------------+------------------------------------------+
1736| ``ACS_ULCORNER`` | upper left corner                        |
1737+------------------+------------------------------------------+
1738| ``ACS_URCORNER`` | upper right corner                       |
1739+------------------+------------------------------------------+
1740| ``ACS_VLINE``    | vertical line                            |
1741+------------------+------------------------------------------+
1742
1743The following table lists the predefined colors:
1744
1745+-------------------+----------------------------+
1746| Constant          | Color                      |
1747+===================+============================+
1748| ``COLOR_BLACK``   | Black                      |
1749+-------------------+----------------------------+
1750| ``COLOR_BLUE``    | Blue                       |
1751+-------------------+----------------------------+
1752| ``COLOR_CYAN``    | Cyan (light greenish blue) |
1753+-------------------+----------------------------+
1754| ``COLOR_GREEN``   | Green                      |
1755+-------------------+----------------------------+
1756| ``COLOR_MAGENTA`` | Magenta (purplish red)     |
1757+-------------------+----------------------------+
1758| ``COLOR_RED``     | Red                        |
1759+-------------------+----------------------------+
1760| ``COLOR_WHITE``   | White                      |
1761+-------------------+----------------------------+
1762| ``COLOR_YELLOW``  | Yellow                     |
1763+-------------------+----------------------------+
1764
1765
1766:mod:`curses.textpad` --- Text input widget for curses programs
1767===============================================================
1768
1769.. module:: curses.textpad
1770   :synopsis: Emacs-like input editing in a curses window.
1771.. moduleauthor:: Eric Raymond <esr@thyrsus.com>
1772.. sectionauthor:: Eric Raymond <esr@thyrsus.com>
1773
1774
1775The :mod:`curses.textpad` module provides a :class:`Textbox` class that handles
1776elementary text editing in a curses window, supporting a set of keybindings
1777resembling those of Emacs (thus, also of Netscape Navigator, BBedit 6.x,
1778FrameMaker, and many other programs).  The module also provides a
1779rectangle-drawing function useful for framing text boxes or for other purposes.
1780
1781The module :mod:`curses.textpad` defines the following function:
1782
1783
1784.. function:: rectangle(win, uly, ulx, lry, lrx)
1785
1786   Draw a rectangle.  The first argument must be a window object; the remaining
1787   arguments are coordinates relative to that window.  The second and third
1788   arguments are the y and x coordinates of the upper left hand corner of the
1789   rectangle to be drawn; the fourth and fifth arguments are the y and x
1790   coordinates of the lower right hand corner. The rectangle will be drawn using
1791   VT100/IBM PC forms characters on terminals that make this possible (including
1792   xterm and most other software terminal emulators).  Otherwise it will be drawn
1793   with ASCII  dashes, vertical bars, and plus signs.
1794
1795
1796.. _curses-textpad-objects:
1797
1798Textbox objects
1799---------------
1800
1801You can instantiate a :class:`Textbox` object as follows:
1802
1803
1804.. class:: Textbox(win)
1805
1806   Return a textbox widget object.  The *win* argument should be a curses
1807   :ref:`window <curses-window-objects>` object in which the textbox is to
1808   be contained. The edit cursor of the textbox is initially located at the
1809   upper left hand corner of the containing window, with coordinates ``(0, 0)``.
1810   The instance's :attr:`stripspaces` flag is initially on.
1811
1812   :class:`Textbox` objects have the following methods:
1813
1814
1815   .. method:: edit([validator])
1816
1817      This is the entry point you will normally use.  It accepts editing
1818      keystrokes until one of the termination keystrokes is entered.  If
1819      *validator* is supplied, it must be a function.  It will be called for
1820      each keystroke entered with the keystroke as a parameter; command dispatch
1821      is done on the result. This method returns the window contents as a
1822      string; whether blanks in the window are included is affected by the
1823      :attr:`stripspaces` attribute.
1824
1825
1826   .. method:: do_command(ch)
1827
1828      Process a single command keystroke.  Here are the supported special
1829      keystrokes:
1830
1831      +------------------+-------------------------------------------+
1832      | Keystroke        | Action                                    |
1833      +==================+===========================================+
1834      | :kbd:`Control-A` | Go to left edge of window.                |
1835      +------------------+-------------------------------------------+
1836      | :kbd:`Control-B` | Cursor left, wrapping to previous line if |
1837      |                  | appropriate.                              |
1838      +------------------+-------------------------------------------+
1839      | :kbd:`Control-D` | Delete character under cursor.            |
1840      +------------------+-------------------------------------------+
1841      | :kbd:`Control-E` | Go to right edge (stripspaces off) or end |
1842      |                  | of line (stripspaces on).                 |
1843      +------------------+-------------------------------------------+
1844      | :kbd:`Control-F` | Cursor right, wrapping to next line when  |
1845      |                  | appropriate.                              |
1846      +------------------+-------------------------------------------+
1847      | :kbd:`Control-G` | Terminate, returning the window contents. |
1848      +------------------+-------------------------------------------+
1849      | :kbd:`Control-H` | Delete character backward.                |
1850      +------------------+-------------------------------------------+
1851      | :kbd:`Control-J` | Terminate if the window is 1 line,        |
1852      |                  | otherwise insert newline.                 |
1853      +------------------+-------------------------------------------+
1854      | :kbd:`Control-K` | If line is blank, delete it, otherwise    |
1855      |                  | clear to end of line.                     |
1856      +------------------+-------------------------------------------+
1857      | :kbd:`Control-L` | Refresh screen.                           |
1858      +------------------+-------------------------------------------+
1859      | :kbd:`Control-N` | Cursor down; move down one line.          |
1860      +------------------+-------------------------------------------+
1861      | :kbd:`Control-O` | Insert a blank line at cursor location.   |
1862      +------------------+-------------------------------------------+
1863      | :kbd:`Control-P` | Cursor up; move up one line.              |
1864      +------------------+-------------------------------------------+
1865
1866      Move operations do nothing if the cursor is at an edge where the movement
1867      is not possible.  The following synonyms are supported where possible:
1868
1869      +------------------------+------------------+
1870      | Constant               | Keystroke        |
1871      +========================+==================+
1872      | :const:`KEY_LEFT`      | :kbd:`Control-B` |
1873      +------------------------+------------------+
1874      | :const:`KEY_RIGHT`     | :kbd:`Control-F` |
1875      +------------------------+------------------+
1876      | :const:`KEY_UP`        | :kbd:`Control-P` |
1877      +------------------------+------------------+
1878      | :const:`KEY_DOWN`      | :kbd:`Control-N` |
1879      +------------------------+------------------+
1880      | :const:`KEY_BACKSPACE` | :kbd:`Control-h` |
1881      +------------------------+------------------+
1882
1883      All other keystrokes are treated as a command to insert the given
1884      character and move right (with line wrapping).
1885
1886
1887   .. method:: gather()
1888
1889      Return the window contents as a string; whether blanks in the
1890      window are included is affected by the :attr:`stripspaces` member.
1891
1892
1893   .. attribute:: stripspaces
1894
1895      This attribute is a flag which controls the interpretation of blanks in
1896      the window.  When it is on, trailing blanks on each line are ignored; any
1897      cursor motion that would land the cursor on a trailing blank goes to the
1898      end of that line instead, and trailing blanks are stripped when the window
1899      contents are gathered.
1900