Search code examples
python-3.xutf-8cursespython-curses

Write an UTF8 character to the last position of the screen with Python curses


How to write a UTF8 character to the last position (bottom right) of the screen with Python's curses module?

The task might look straight forward at first, but it isn't. First of all, Python 2.x is incapable of outputting UTF-8 using curses, so we'll assume Python 3.x here. There are two obvious candidates for doing it:

screen.insch(lines - 1, columns - 1, u"\u00a9")

This gives an OverflowError: byte doesn't fit in chtype. Bummer. What about:

screen.addch(lines - 1, columns - 1, u"\u00a9")

While this works, it also scrolls the screen. So we actually wrote to the last column of the second last line. Still the last column of the last line, doesn't have our character.

For most positions, addch works just fine, but not for the last one. insch looks just broken for UTF8.


Solution

  • It's straightforward:

    • turn off scrolling using scrollok
    • move to the lower right corner
    • add the character with addch
    • catch (and ignore) an exception due to failed move past the lower-right corner.

    ncurses does the necessary juggling with insertion...