Unable to create scrollable editor window using curses

Andy Elvey andy.elvey at paradise.net.nz
Sun Sep 27 04:50:14 EDT 2009


Hi all -

I've been trying to create a simple text editor using the curses module.
Doing the basic editor functionality is easy enough (thanks to the 
built-in textpad library), but I'm having real problems getting the text 
to scroll up when the bottom of the page is reached. 

When the user is on the bottom line of the window, the text should 
scroll when they press Enter (or when they hit the end of the bottom line).

This is my code as it is at present (apologies if the code gets mangled 
in the email..... )
By the way, if anything in this seems "odd", my answer to the question 
"why did you do this?"  is - 
"because I didn't know any better.... ;)   " 


*** Start of code *****
import sys, curses, curses.wrapper, curses.ascii, curses.textpad, \
   traceback, string, os
    
def draw(): 
  # Start at top-left of screen  
  x = y = 0  
  # Create a new window
  mywin = curses.newwin(23, 80, y, x)
  mywin.idlok(1)
  mywin.scrollok(1)
  mywin.setscrreg(1, 20)  
  mywin.box() 
  mywin.addstr(0, 25, "*** P.D. Editor ***")  
  mywin.refresh()
 
  # A subwindow. This stops us from over-writing the main window. 
  mywin2 = mywin.subwin(21, 77, y+1, x+1)   
  mywin2.refresh()
 
  # An editor in the subwindow.
  myeditor = curses.textpad.Textbox(mywin2)
  myeditor.edit()
  # Get the position of the cursor and see if we need to scroll the text.
  pos = mywin2.getyx()
  if pos[0] >= 20:       
     mywin2.scroll(1)
  else:
     pass        
  
def main(stdscr):         
    while 1:
      draw()
   
   
#  Run the code from the command-line
if __name__ == '__main__': 
  try:
     stdscr = curses.initscr()  
     curses.noecho() ; curses.cbreak()
     stdscr.keypad(1)
     main(stdscr)      # Enter the main loop
     # Set everything back to normal
     stdscr.keypad(0)
     curses.echo() ; curses.nocbreak()
     curses.endwin()  # Terminate curses
  except:
     # In the event of an error, restore the terminal
     # to a sane state.
     stdscr.keypad(0)
     curses.echo() ; curses.nocbreak()
     curses.endwin()
     traceback.print_exc()  # Print the exception

****  End of code ****** 

I've tried all sorts of things, including having all kinds of 
contortions with pads, subpads and so on.  Nothing has worked, so any 
help with this (so that the editor can be made to scroll the text) would 
be very gratefully received.  Many thanks in advance -
- Andy




More information about the Python-list mailing list