textpad.py 7.17 KB
Newer Older
Andrew M. Kuchling's avatar
Andrew M. Kuchling committed
1
"""Simple textbox editing widget with Emacs-like keybindings."""
2

Georg Brandl's avatar
Georg Brandl committed
3 4
import curses
import curses.ascii
5 6

def rectangle(win, uly, ulx, lry, lrx):
7 8 9
    """Draw a rectangle with corners at the provided upper-left
    and lower-right coordinates.
    """
10 11 12 13 14 15 16 17 18
    win.vline(uly+1, ulx, curses.ACS_VLINE, lry - uly - 1)
    win.hline(uly, ulx+1, curses.ACS_HLINE, lrx - ulx - 1)
    win.hline(lry, ulx+1, curses.ACS_HLINE, lrx - ulx - 1)
    win.vline(uly+1, lrx, curses.ACS_VLINE, lry - uly - 1)
    win.addch(uly, ulx, curses.ACS_ULCORNER)
    win.addch(uly, lrx, curses.ACS_URCORNER)
    win.addch(lry, lrx, curses.ACS_LRCORNER)
    win.addch(lry, ulx, curses.ACS_LLCORNER)

19
class Textbox:
20 21 22 23 24 25
    """Editing widget using the interior of a window object.
     Supports the following Emacs-like key bindings:

    Ctrl-A      Go to left edge of window.
    Ctrl-B      Cursor left, wrapping to previous line if appropriate.
    Ctrl-D      Delete character under cursor.
26
    Ctrl-E      Go to right edge (stripspaces off) or end of line (stripspaces on).
27 28
    Ctrl-F      Cursor right, wrapping to next line when appropriate.
    Ctrl-G      Terminate, returning the window contents.
29
    Ctrl-H      Delete character backward.
30 31
    Ctrl-J      Terminate if the window is 1 line, otherwise insert newline.
    Ctrl-K      If line is blank, delete it, otherwise clear to end of line.
32
    Ctrl-L      Refresh screen.
33 34 35 36 37 38 39 40
    Ctrl-N      Cursor down; move down one line.
    Ctrl-O      Insert a blank line at cursor location.
    Ctrl-P      Cursor up; move up one line.

    Move operations do nothing if the cursor is at an edge where the movement
    is not possible.  The following synonyms are supported where possible:

    KEY_LEFT = Ctrl-B, KEY_RIGHT = Ctrl-F, KEY_UP = Ctrl-P, KEY_DOWN = Ctrl-N
41
    KEY_BACKSPACE = Ctrl-h
42
    """
43
    def __init__(self, win, insert_mode=False):
44
        self.win = win
45
        self.insert_mode = insert_mode
46 47 48 49
        (self.maxy, self.maxx) = win.getmaxyx()
        self.maxy = self.maxy - 1
        self.maxx = self.maxx - 1
        self.stripspaces = 1
50
        self.lastcmd = None
51 52
        win.keypad(1)

53
    def _end_of_line(self, y):
54 55
        """Go to the location of the first blank on the given line,
        returning the index of the last non-blank character."""
56
        last = self.maxx
57
        while True:
Georg Brandl's avatar
Georg Brandl committed
58
            if curses.ascii.ascii(self.win.inch(y, last)) != curses.ascii.SP:
59
                last = min(self.maxx, last+1)
60
                break
61 62
            elif last == 0:
                break
63 64 65
            last = last - 1
        return last

66 67 68 69 70 71 72 73 74 75 76 77 78 79
    def _insert_printable_char(self, ch):
        (y, x) = self.win.getyx()
        if y < self.maxy or x < self.maxx:
            if self.insert_mode:
                oldch = self.win.inch()
            # The try-catch ignores the error we trigger from some curses
            # versions by trying to write into the lowest-rightmost spot
            # in the window.
            try:
                self.win.addch(ch)
            except curses.error:
                pass
            if self.insert_mode:
                (backy, backx) = self.win.getyx()
Georg Brandl's avatar
Georg Brandl committed
80
                if curses.ascii.isprint(oldch):
81 82 83
                    self._insert_printable_char(oldch)
                    self.win.move(backy, backx)

84 85 86
    def do_command(self, ch):
        "Process a single editing command."
        (y, x) = self.win.getyx()
87
        self.lastcmd = ch
Georg Brandl's avatar
Georg Brandl committed
88
        if curses.ascii.isprint(ch):
89
            if y < self.maxy or x < self.maxx:
90
                self._insert_printable_char(ch)
Georg Brandl's avatar
Georg Brandl committed
91
        elif ch == curses.ascii.SOH:                           # ^a
92
            self.win.move(y, 0)
Georg Brandl's avatar
Georg Brandl committed
93
        elif ch in (curses.ascii.STX,curses.KEY_LEFT, curses.ascii.BS,curses.KEY_BACKSPACE):
94 95 96 97 98
            if x > 0:
                self.win.move(y, x-1)
            elif y == 0:
                pass
            elif self.stripspaces:
99
                self.win.move(y-1, self._end_of_line(y-1))
100 101
            else:
                self.win.move(y-1, self.maxx)
Georg Brandl's avatar
Georg Brandl committed
102
            if ch in (curses.ascii.BS, curses.KEY_BACKSPACE):
103
                self.win.delch()
Georg Brandl's avatar
Georg Brandl committed
104
        elif ch == curses.ascii.EOT:                           # ^d
105
            self.win.delch()
Georg Brandl's avatar
Georg Brandl committed
106
        elif ch == curses.ascii.ENQ:                           # ^e
107
            if self.stripspaces:
108
                self.win.move(y, self._end_of_line(y))
109 110
            else:
                self.win.move(y, self.maxx)
Georg Brandl's avatar
Georg Brandl committed
111
        elif ch in (curses.ascii.ACK, curses.KEY_RIGHT):       # ^f
112 113
            if x < self.maxx:
                self.win.move(y, x+1)
114
            elif y == self.maxy:
115 116 117
                pass
            else:
                self.win.move(y+1, 0)
Georg Brandl's avatar
Georg Brandl committed
118
        elif ch == curses.ascii.BEL:                           # ^g
119
            return 0
Georg Brandl's avatar
Georg Brandl committed
120
        elif ch == curses.ascii.NL:                            # ^j
121 122 123 124
            if self.maxy == 0:
                return 0
            elif y < self.maxy:
                self.win.move(y+1, 0)
Georg Brandl's avatar
Georg Brandl committed
125
        elif ch == curses.ascii.VT:                            # ^k
126
            if x == 0 and self._end_of_line(y) == 0:
127 128
                self.win.deleteln()
            else:
129 130
                # first undo the effect of self._end_of_line
                self.win.move(y, x)
131
                self.win.clrtoeol()
Georg Brandl's avatar
Georg Brandl committed
132
        elif ch == curses.ascii.FF:                            # ^l
133
            self.win.refresh()
Georg Brandl's avatar
Georg Brandl committed
134
        elif ch in (curses.ascii.SO, curses.KEY_DOWN):         # ^n
135 136
            if y < self.maxy:
                self.win.move(y+1, x)
137 138
                if x > self._end_of_line(y+1):
                    self.win.move(y+1, self._end_of_line(y+1))
Georg Brandl's avatar
Georg Brandl committed
139
        elif ch == curses.ascii.SI:                            # ^o
140
            self.win.insertln()
Georg Brandl's avatar
Georg Brandl committed
141
        elif ch in (curses.ascii.DLE, curses.KEY_UP):          # ^p
142 143
            if y > 0:
                self.win.move(y-1, x)
144 145
                if x > self._end_of_line(y-1):
                    self.win.move(y-1, self._end_of_line(y-1))
146
        return 1
147

148 149 150 151 152
    def gather(self):
        "Collect and return the contents of the window."
        result = ""
        for y in range(self.maxy+1):
            self.win.move(y, 0)
153
            stop = self._end_of_line(y)
154 155 156
            if stop == 0 and self.stripspaces:
                continue
            for x in range(self.maxx+1):
157
                if self.stripspaces and x > stop:
158
                    break
Georg Brandl's avatar
Georg Brandl committed
159
                result = result + chr(curses.ascii.ascii(self.win.inch(y, x)))
160 161 162 163 164 165 166 167 168 169
            if self.maxy > 0:
                result = result + "\n"
        return result

    def edit(self, validate=None):
        "Edit in the widget window and collect the results."
        while 1:
            ch = self.win.getch()
            if validate:
                ch = validate(ch)
170 171
            if not ch:
                continue
172 173
            if not self.do_command(ch):
                break
174
            self.win.refresh()
175 176 177 178
        return self.gather()

if __name__ == '__main__':
    def test_editbox(stdscr):
179 180
        ncols, nlines = 9, 4
        uly, ulx = 15, 20
181
        stdscr.addstr(uly-2, ulx, "Use Ctrl-G to end editing.")
182 183
        win = curses.newwin(nlines, ncols, uly, ulx)
        rectangle(stdscr, uly-1, ulx-1, uly + nlines, ulx + ncols)
184
        stdscr.refresh()
185
        return Textbox(win).edit()
186 187

    str = curses.wrapper(test_editbox)
188
    print('Contents of text box:', repr(str))