Debian Codegraph @

Lib/curses/textpad.py

raw
1 """Simple textbox editing widget with Emacs-like keybindings."""
2
3 import curses
4 import curses.ascii
5
6 def rectangle(win, uly, ulx, lry, lrx):
7 """Draw a rectangle with corners at the provided upper-left
8 and lower-right coordinates.
9 """
10 win.vline(uly+1, ulx, curses.ACS_VLINE, lry - uly - 1)
11 win.hline(uly, ulx+1, curses.ACS_HLINE, lrx - ulx - 1)
12 win.hline(lry, ulx+1, curses.ACS_HLINE, lrx - ulx - 1)
13 win.vline(uly+1, lrx, curses.ACS_VLINE, lry - uly - 1)
14 win.addch(uly, ulx, curses.ACS_ULCORNER)
15 win.addch(uly, lrx, curses.ACS_URCORNER)
16 win.addch(lry, lrx, curses.ACS_LRCORNER)
17 win.addch(lry, ulx, curses.ACS_LLCORNER)
18
19 class Textbox:
20 """Editing widget using the interior of a window object.
21 Supports the following Emacs-like key bindings:
22
23 Ctrl-A Go to left edge of window.
24 Ctrl-B Cursor left, wrapping to previous line if appropriate.
25 Ctrl-D Delete character under cursor.
26 Ctrl-E Go to right edge (stripspaces off) or end of line
27 (stripspaces on).
28 Ctrl-F Cursor right, wrapping to next line when appropriate.
29 Ctrl-G Terminate, returning the window contents.
30 Ctrl-H Delete character backward.
31 Ctrl-J Terminate if the window is 1 line, otherwise insert newline.
32 Ctrl-K If line is blank, delete it, otherwise clear to end of line.
33 Ctrl-L Refresh screen.
34 Ctrl-N Cursor down; move down one line.
35 Ctrl-O Insert a blank line at cursor location.
36 Ctrl-P Cursor up; move up one line.
37
38 Move operations do nothing if the cursor is at an edge where the
39 movement is not possible. The following synonyms are supported where
40 possible:
41
42 KEY_LEFT = Ctrl-B, KEY_RIGHT = Ctrl-F, KEY_UP = Ctrl-P,
43 KEY_DOWN = Ctrl-N, KEY_BACKSPACE = Ctrl-h
44 """
45 def __init__(self, win, insert_mode=False):
46 self.win = win
47 self.insert_mode = insert_mode
48 self._update_max_yx()
49 self.stripspaces = 1
50 self.lastcmd = None
51 win.keypad(1)
52
53 def _update_max_yx(self):
54 maxy, maxx = self.win.getmaxyx()
55 self.maxy = maxy - 1
56 self.maxx = maxx - 1
57
58 def _end_of_line(self, y):
59 """Go to the location of the first blank on the given line,
60 returning the index of the last non-blank character."""
61 self._update_max_yx()
62 last = self.maxx
63 while True:
64 if curses.ascii.ascii(self.win.inch(y, last)) != curses.ascii.SP:
65 last = min(self.maxx, last+1)
66 break
67 elif last == 0:
68 break
69 last = last - 1
70 return last
71
72 def _insert_printable_char(self, ch):
73 self._update_max_yx()
74 (y, x) = self.win.getyx()
75 backyx = None
76 while y < self.maxy or x < self.maxx:
77 if self.insert_mode:
78 oldch = self.win.inch()
79 # The try-catch ignores the error we trigger from some curses
80 # versions by trying to write into the lowest-rightmost spot
81 # in the window.
82 try:
83 self.win.addch(ch)
84 except curses.error:
85 pass
86 if not self.insert_mode or not curses.ascii.isprint(oldch):
87 break
88 ch = oldch
89 (y, x) = self.win.getyx()
90 # Remember where to put the cursor back since we are in insert_mode
91 if backyx is None:
92 backyx = y, x
93
94 if backyx is not None:
95 self.win.move(*backyx)
96
97 def do_command(self, ch):
98 "Process a single editing command."
99 self._update_max_yx()
100 (y, x) = self.win.getyx()
101 self.lastcmd = ch
102 if curses.ascii.isprint(ch):
103 if y < self.maxy or x < self.maxx:
104 self._insert_printable_char(ch)
105 elif ch == curses.ascii.SOH: # ^a
106 self.win.move(y, 0)
107 elif ch in (curses.ascii.STX,curses.KEY_LEFT,
108 curses.ascii.BS,
109 curses.KEY_BACKSPACE,
110 curses.ascii.DEL):
111 if x > 0:
112 self.win.move(y, x-1)
113 elif y == 0:
114 pass
115 elif self.stripspaces:
116 self.win.move(y-1, self._end_of_line(y-1))
117 else:
118 self.win.move(y-1, self.maxx)
119 if ch in (curses.ascii.BS, curses.KEY_BACKSPACE, curses.ascii.DEL):
120 self.win.delch()
121 elif ch == curses.ascii.EOT: # ^d
122 self.win.delch()
123 elif ch == curses.ascii.ENQ: # ^e
124 if self.stripspaces:
125 self.win.move(y, self._end_of_line(y))
126 else:
127 self.win.move(y, self.maxx)
128 elif ch in (curses.ascii.ACK, curses.KEY_RIGHT): # ^f
129 if x < self.maxx:
130 self.win.move(y, x+1)
131 elif y == self.maxy:
132 pass
133 else:
134 self.win.move(y+1, 0)
135 elif ch == curses.ascii.BEL: # ^g
136 return 0
137 elif ch == curses.ascii.NL: # ^j
138 if self.maxy == 0:
139 return 0
140 elif y < self.maxy:
141 self.win.move(y+1, 0)
142 elif ch == curses.ascii.VT: # ^k
143 if x == 0 and self._end_of_line(y) == 0:
144 self.win.deleteln()
145 else:
146 # first undo the effect of self._end_of_line
147 self.win.move(y, x)
148 self.win.clrtoeol()
149 elif ch == curses.ascii.FF: # ^l
150 self.win.refresh()
151 elif ch in (curses.ascii.SO, curses.KEY_DOWN): # ^n
152 if y < self.maxy:
153 self.win.move(y+1, x)
154 if x > self._end_of_line(y+1):
155 self.win.move(y+1, self._end_of_line(y+1))
156 elif ch == curses.ascii.SI: # ^o
157 self.win.insertln()
158 elif ch in (curses.ascii.DLE, curses.KEY_UP): # ^p
159 if y > 0:
160 self.win.move(y-1, x)
161 if x > self._end_of_line(y-1):
162 self.win.move(y-1, self._end_of_line(y-1))
163 return 1
164
165 def gather(self):
166 "Collect and return the contents of the window."
167 result = ""
168 self._update_max_yx()
169 for y in range(self.maxy+1):
170 self.win.move(y, 0)
171 stop = self._end_of_line(y)
172 if stop == 0 and self.stripspaces:
173 continue
174 for x in range(self.maxx+1):
175 if self.stripspaces and x > stop:
176 break
177 result = result + chr(curses.ascii.ascii(self.win.inch(y, x)))
178 if self.maxy > 0:
179 result = result + "\n"
180 return result
181
182 def edit(self, validate=None):
183 "Edit in the widget window and collect the results."
184 while 1:
185 ch = self.win.getch()
186 if validate:
187 ch = validate(ch)
188 if not ch:
189 continue
190 if not self.do_command(ch):
191 break
192 self.win.refresh()
193 return self.gather()
194
195 if __name__ == '__main__':
196 def test_editbox(stdscr):
197 ncols, nlines = 9, 4
198 uly, ulx = 15, 20
199 stdscr.addstr(uly-2, ulx, "Use Ctrl-G to end editing.")
200 win = curses.newwin(nlines, ncols, uly, ulx)
201 rectangle(stdscr, uly-1, ulx-1, uly + nlines, ulx + ncols)
202 stdscr.refresh()
203 return Textbox(win).edit()
204
205 str = curses.wrapper(test_editbox)
206 print('Contents of text box:', repr(str))