pythonpython-curses

Python curses Textbox.gather() removes empty lines, is there a way to preserve them?


In below code box.gather() removes empty lines from text. Is there a way to collect the text as is including empty lines?

from curses import wrapper
from curses.textpad import Textbox

def main(stdscr):
   stdscr.addstr(0, 0, "Enter text separated by empty lines: (hit Ctrl-G to send)")
   box = Textbox(stdscr)
   box.edit()
   return box.gather()
   

if __name__ == '__main__':
    s = wrapper(main)
    print(s)

Solution

  • Textbox object contain stripspaces attribute which handles this behaviour.

    From documentation:

    stripspaces

    This attribute is a flag which controls the interpretation of blanks in the window. When it is on, trailing blanks on each line are ignored; any cursor motion that would land the cursor on a trailing blank goes to the end of that line instead, and trailing blanks are stripped when the window contents are gathered.

    So, your final code will look like this:

    from curses import wrapper
    from curses.textpad import Textbox
    
    def main(stdscr):
       stdscr.addstr(0, 0, "Enter text separated by empty lines: (hit Ctrl-G to send)")
       box = Textbox(stdscr)
       box.stripspaces = False
       box.edit()
       return box.gather()
       
    
    if __name__ == '__main__':
        s = wrapper(main)
        print(s)