textpad.py 7.48 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
        self._update_max_yx()
47
        self.stripspaces = 1
48
        self.lastcmd = None
49 50
        win.keypad(1)

51 52 53 54 55
    def _update_max_yx(self):
        maxy, maxx = self.win.getmaxyx()
        self.maxy = maxy - 1
        self.maxx = maxx - 1

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

70
    def _insert_printable_char(self, ch):
71
        self._update_max_yx()
72
        (y, x) = self.win.getyx()
73 74
        backyx = None
        while y < self.maxy or x < self.maxx:
75 76 77 78 79 80 81 82 83
            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
84 85 86 87 88 89 90 91 92 93
            if not self.insert_mode or not curses.ascii.isprint(oldch):
                break
            ch = oldch
            (y, x) = self.win.getyx()
            # Remember where to put the cursor back since we are in insert_mode
            if backyx is None:
                backyx = y, x

        if backyx is not None:
            self.win.move(*backyx)
94

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

160 161 162
    def gather(self):
        "Collect and return the contents of the window."
        result = ""
163
        self._update_max_yx()
164 165
        for y in range(self.maxy+1):
            self.win.move(y, 0)
166
            stop = self._end_of_line(y)
167 168 169
            if stop == 0 and self.stripspaces:
                continue
            for x in range(self.maxx+1):
170
                if self.stripspaces and x > stop:
171
                    break
Georg Brandl's avatar
Georg Brandl committed
172
                result = result + chr(curses.ascii.ascii(self.win.inch(y, x)))
173 174 175 176 177 178 179 180 181 182
            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)
183 184
            if not ch:
                continue
185 186
            if not self.do_command(ch):
                break
187
            self.win.refresh()
188 189 190 191
        return self.gather()

if __name__ == '__main__':
    def test_editbox(stdscr):
192 193
        ncols, nlines = 9, 4
        uly, ulx = 15, 20
194
        stdscr.addstr(uly-2, ulx, "Use Ctrl-G to end editing.")
195 196
        win = curses.newwin(nlines, ncols, uly, ulx)
        rectangle(stdscr, uly-1, ulx-1, uly + nlines, ulx + ncols)
197
        stdscr.refresh()
198
        return Textbox(win).edit()
199 200

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