Debian Codegraph @

libsrc/text/line-edit.scm

raw
1 ;;;
2 ;;; text.line-edit - line editing
3 ;;;
4 ;;; Copyright (c) 2015-2024 Shiro Kawai <[email protected]>
5 ;;;
6 ;;; Redistribution and use in source and binary forms, with or without
7 ;;; modification, are permitted provided that the following conditions
8 ;;; are met:
9 ;;;
10 ;;; 1. Redistributions of source code must retain the above copyright
11 ;;; notice, this list of conditions and the following disclaimer.
12 ;;;
13 ;;; 2. Redistributions in binary form must reproduce the above copyright
14 ;;; notice, this list of conditions and the following disclaimer in the
15 ;;; documentation and/or other materials provided with the distribution.
16 ;;;
17 ;;; 3. Neither the name of the authors nor the names of its contributors
18 ;;; may be used to endorse or promote products derived from this
19 ;;; software without specific prior written permission.
20 ;;;
21 ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 ;;;
33
34 (define-module text.line-edit
35 (use gauche.generator)
36 (use gauche.threads)
37 (use gauche.sequence)
38 (use gauche.unicode)
39 (use data.ring-buffer)
40 (use data.queue)
41 (use file.util)
42 (use util.match)
43 (use text.console)
44 (use text.console.wide-char-setting)
45 (use text.gap-buffer)
46 (use text.pager)
47 (export <line-edit-context> read-line/edit
48 save-line-edit-history
49 load-line-edit-history
50
51 default-keymap
52 command-name->keystrokes
53 command-name->keystroke-string)
54 )
55 (select-module text.line-edit)
56
57 (autoload text.external-editor ed-string)
58 (autoload text.console.framebuffer <framebuffer-console>
59 init-framebuffer
60 draw-framebuffer)
61 (autoload text.multicolumn display-multicolumn)
62
63 (define *kill-ring-size* 60)
64 (define *history-size* 200)
65
66 ;; <line-edit-context>
67 ;; Initializable slots:
68 ;; console - <console> object to use. if omitted, make-default-console
69 ;; is called (see text.console)
70 ;; prompt - a string or a thunk that returns a string.
71 ;; keymap - a keymap to map keystroke -> command.
72 ;; input-continues - if this is #f, commit-or-newline always
73 ;; commit the line---that read-line/edit strictly works as
74 ;; line editor. Otherwise, this should be a procedure that
75 ;; takes the current buffer content as a string, and should
76 ;; return #f if the input is complete, or #t otherwise.
77 ;; If the procedure returns #t, commit-or-newline inserts a
78 ;; newline to the buffer and enters multiline edit mode.
79 ;; tab-char-width - a tab character width.
80 ;; wide-char-disp-setting - <wide-char-setting> object to configure
81 ;; a wide character setting for display.
82 ;; wide-char-pos-setting - <wide-char-setting> object to configure
83 ;; a wide character setting for cursor movement.
84 ;;
85 (define-class <line-edit-context> ()
86 ((console :init-keyword :console :init-form (make-default-console))
87 (prompt :init-keyword :prompt :init-value "")
88 (keymap :init-keyword :keymap :init-form (default-keymap))
89 (input-continues :init-keyword :input-continues :init-form #f)
90 (tab-char-width :init-keyword :tab-char-width :init-value 8)
91 (wide-char-disp-setting :init-keyword :wide-char-disp-setting
92 :init-form (make <wide-char-setting>))
93 (wide-char-pos-setting :init-keyword :wide-char-pos-setting
94 :init-form (make <wide-char-setting>))
95
96 ;; A predicate or a char-set to determine word constituent characters
97 (completion-word-constituent? :init-keyword :completion-word-constituent?
98 :init-value #[-\w])
99 ;; <^ <string> <gap-buffer> <integer> <integer>
100 ;; -> </ <string> <List <string>>>
101 ;; Returns completion candidate(s) that match the given word.
102 ;; If a single final completed value is determined, it is returned as
103 ;; a string. Otherwise, a list of candidates (including zero or one
104 ;; cases) is returned. The difference between a single string and
105 ;; a list of a string is that the latter needs further completion
106 ;; (e.g. complete to a directory boundary; further completion will go
107 ;; down to the directory).
108 (completion-lister :init-keyword :completion-lister :init-value #f)
109
110 ;; Following slots are private.
111 ;; When we enter read/edit, we record the cursor position and screen size.
112 (initpos-y)
113 (initpos-x)
114 (screen-height)
115 (screen-width)
116
117 ;; These are the cursor position immediately before a command is invoked
118 ;; (or, more precisely, the cursor position after the last redraw).
119 (lastpos-y)
120 (lastpos-x)
121
122 ;; A position of a highlighting parenthesis
123 (paren-pos :init-value #f)
124
125 ;; The last executed editor command. Completion command behaves differently
126 ;; if invoked more than once immediately.
127 (last-command :init-value #f)
128
129 ;; Experimental framebuffer support. Only enabled by the env var.
130 (framebuffer :init-form (and (sys-getenv "GAUCHE_READ_EDIT_WITH_FB")
131 (make <framebuffer-console>)))
132
133 ;; Selection
134 ;; selection is between marker-pos and the current cursor pos.
135 ;; maker-pos == #f means no selection.
136 (marker-pos :init-value #f)
137
138 ;; Kill and yank
139 ;; Kill ring survives across sessions. Last-yank-* is reset after
140 ;; every command except yank and yank-pop.
141 (kill-ring :init-form (make-ring-buffer
142 (make-vector *kill-ring-size*)
143 :overflow-handler 'overwrite))
144 (last-yank :init-value -1) ; index into the kill-ring buffer. -1 means
145 ; last op wasn't yank.
146 (last-yank-pos :init-value 0) ; index into buffer where last yank is put.
147 (last-yank-size :init-value 0)
148
149 ;; Undo
150 ;; See the comment at the bottom. In the normal state, redo-queue is
151 ;; empty and undo-stack has the stack of edit commands to undo the changes.
152 ;; Redo-queue is non-empty when we're in the middle of undo sequence.
153 (undo-stack :init-form (make-queue))
154 (redo-queue :init-form (make-queue))
155
156 ;; Keyboard input
157 ;; timer-callback is, if set, fired after waiting for keyboard input
158 ;; for 1 sec, or a new keyboard input, whichever comes first. It is
159 ;; invoked with the key input or #f (timeout); it is one-shot, so
160 ;; automatially cleared.
161 (keystroke-queue :init-form (make-queue))
162 (timed-callback :init-value #f)
163
164 ;; History
165 ;; Global history is kept in the ring buffer, index 0 being the most recent.
166 ;; History-pos is the index to the last recalled history; -1 indicates
167 ;; we're editing the fresh line instead of the one recalled from history.
168 ;; The history-transient is a hashtable indexed by history-pos and holds
169 ;; the line and undo-stack; see below.
170 (history :init-form (make-ring-buffer
171 (make-vector *history-size*)
172 :overflow-handler 'overwrite))
173 (history-pos :init-value -1)
174 (history-transient :init-value #f)
175 ))
176
177 (define (%load-history ctx path)
178 (with-input-from-file path
179 (^[]
180 (read) ; ignore version for now
181 (do-generator [line read-line] ; for now, one sexpr per line
182 (guard (e [else #f])
183 (commit-history ctx
184 (string->gap-buffer
185 (call-with-input-string line read))))))
186 :if-does-not-exist #f))
187
188 (define (load-line-edit-history ctx path)
189 (guard (e [else
190 (display "failed to read history: " (current-error-port))
191 (display e (current-error-port))
192 (display #\newline (current-error-port))])
193 (%load-history ctx path)))
194
195 (define (%save-history ctx path)
196 (call-with-temporary-file
197 (^[port name]
198 (write '(gauche-history-version 1) port)
199 (display #\newline port)
200 (for-each (^i
201 (write (ring-buffer-ref (~ ctx'history) i) port)
202 (display "\n" port))
203 (reverse (iota (history-size ctx))))
204 (close-output-port port) ;; necessary on MinGW
205 (sys-rename name path))
206 :directory (sys-dirname path)))
207
208 (define (save-line-edit-history ctx path)
209 (guard (e [else
210 (display "failed to save history: " (current-error-port))
211 (display e (current-error-port))
212 (display #\newline (current-error-port))])
213 (%save-history ctx path)))
214
215 ;; Global SIGCONT handler
216 ;; Since we, as a library, don't have control of sigmasks in all threads,
217 ;; so we don't know which thread the sigcont handler is invoked.
218
219 ;; *sigcont-observer* is an atom of these values:
220 ;; - list of threads running read-line/edit
221 ;; - list of threads that haven't handled SIGCONT
222 ;;
223 ;; When SIGCONT handler is called, it copies the first value to the second.
224 ;; When read-line/edit attempt to read from console, it checks the second
225 ;; value to see if the calling thread is in it. If so, remove the thread
226 ;; from it, and reset the console.
227
228 ;; NB: First call to read-line/edit installs global SIGCONT handler.
229 ;; We can't localize the effect. If you want to handle SIGCONT yourself,
230 ;; you can't use read-line/edit. (We may be able to offer an option to
231 ;; handle SIGCONT or not, but it'll be pretty hairy to make it safe.)
232
233 (define *sigcont-observers* (atom '() '()))
234
235 ;; Windows doesn't define SIGCONT, and we precompile this module so we can't
236 ;; use cond-expand.
237 (define *sigcont* (module-binding-ref 'gauche 'SIGCONT 0))
238
239 (define (%sigcont-handler sig)
240 (when (eqv? sig *sigcont*)
241 (atomic-update! *sigcont-observers* (^[ts _] (values ts ts)))))
242
243 (define (%sigcont-observe)
244 (let1 t (current-thread)
245 (atomic-update! *sigcont-observers*
246 (^[ts notifiee]
247 (when (null? ts)
248 (set-signal-handler! *sigcont* %sigcont-handler))
249 (values (if (memq t ts) ts (cons t ts))
250 notifiee)))))
251
252 (define (%sigcont-unobserve)
253 (let1 t (current-thread)
254 (atomic-update! *sigcont-observers*
255 (^[ts notifiee]
256 (let1 ts. (delete t ts)
257 (when (null? ts)
258 (set-signal-handler! *sigcont* #t))
259 (values (delete t ts) notifiee))))))
260
261 (define (%sigcont-received?)
262 (let1 t (current-thread)
263 (values-ref (atomic-update! *sigcont-observers*
264 (^[ts notifiee]
265 (values ts (delete t notifiee)
266 (boolean (memq t notifiee)))))
267 2)))
268
269 ;; Entry point API
270 ;; NB: For the consistency with read-line, the returned string won't include
271 ;; the final newline.
272 (define (read-line/edit ctx)
273 (define buffer (make-gap-buffer))
274 (define (eofread)
275 (if (> (gap-buffer-content-length buffer) 0)
276 (commit-history ctx buffer)
277 (eof-object)))
278 ;; Command handler.
279 ;; The command may return one of the following values.
280 ;; visible - the command changed something visible so we need to
281 ;; redisplay, but we don't need to save the change in
282 ;; the actual buffer.
283 ;; The selection is cleared.
284 ;; unchanged - no change visually and internally; we break
285 ;; undo sequence and reset last yank, but not clear
286 ;; selection.
287 ;; This occurs, for example, backward-char at the
288 ;; beginning of the input.
289 ;; nop - totally ignore the key input.
290 ;; redraw - we won't change the state of the editor, but
291 ;; we reobtain the cursor position before redrawing
292 ;; the buffer content. This is necessary when the command
293 ;; wrote something on the screen and we don't want to clobber
294 ;; it.
295 ;; moved - the command only moved cursor pos. requires redisplay,
296 ;; but we keep selection.
297 ;; #<eof> - end of input - either input port is closed, or
298 ;; the user typed EOT char when the buffer is empty.
299 ;; commit - record the current buffer to the history, and
300 ;; returns it.
301 ;; undone - the command undid the change. we record the fact,
302 ;; for the consecutive undo behaves differently than
303 ;; other commands.
304 ;; <edit-command> - the command changed the buffer contents,
305 ;; and the return value is an edit command to undo the
306 ;; change.
307 ;; (yanked <edit-command>) - this is only returned by yank and yank-pop
308 ;; command.
309 ;;
310 ;; If the key is a character and it is not registered in the table,
311 ;; we treat as if it is associated to the self-insert-command.
312 ;; Given the large character set, it is a reasonable compromise.
313 (define (handle-command h ch loop redisp)
314 (cond
315 [(eof-object? h) (eofread)]
316 [(applicable? h <top> <top> <top>)
317 (match (h ctx buffer ch)
318 [(? eof-object?) (eofread)]
319 ['nop (loop redisp h)]
320 ['visible (reset-last-yank! ctx)
321 (clear-mark! ctx buffer)
322 (break-undo-sequence! ctx)
323 (loop #t h)]
324 ['unchanged (reset-last-yank! ctx)
325 (break-undo-sequence! ctx)
326 (loop redisp h)]
327 ['redraw (reset-cursor-pos ctx)
328 (loop #t h)]
329 ['moved (reset-last-yank! ctx)
330 (break-undo-sequence! ctx)
331 (loop #t h)]
332 ['commit
333 ;; We move the cursor to the last of input and redisplay,
334 ;; so that the output of the client program won't overwrite
335 ;; the existing input.
336 (gap-buffer-move! buffer 0 'end)
337 (redisplay ctx buffer)
338 (putstr (~ ctx'console) "\r\n")
339 (commit-history ctx buffer)]
340 ['undone (reset-last-yank! ctx)
341 (clear-mark! ctx buffer)
342 (loop #t h)] ; don't break undo sequence
343 [('yanked edit-command)
344 (break-undo-sequence! ctx)
345 (clear-mark! ctx buffer)
346 (push-undo! ctx edit-command)
347 (loop #t h)]
348 [(? list? edit-command)
349 (reset-last-yank! ctx)
350 (break-undo-sequence! ctx)
351 (clear-mark! ctx buffer)
352 (push-undo! ctx edit-command)
353 (loop #t h)]
354 [x (error "[internal] invalid return value from a command:" x)])]
355 [(is-a? h <keymap>)
356 (let* ([ch (next-keystroke ctx)]
357 [h (keymap-ref h ch)])
358 (handle-command h ch loop redisp))]
359 [else
360 (error "[internal] do not know how to handle key:" h)]))
361
362 ;; Internal loop
363 ;; Pass true to redisp to cause buffer to be redisplayed before
364 ;; accepting a new edit command.
365 ;; Returns a string or #<eof>
366 (define (edit-loop redisp last-command)
367 ;; NB: If next char is ready, don't bother to redisplay and
368 ;; just carry over redisp flag.
369 (let* ([redisp (if (and redisp (not (chready? (~ ctx'console))))
370 (begin (redisplay ctx buffer) #f)
371 redisp)]
372 [ch (next-keystroke ctx)]
373 [h (keymap-ref (~ ctx'keymap) ch)])
374 (set! (~ ctx'last-command) last-command)
375 (handle-command h ch edit-loop redisp)))
376
377 ;; The 'main' routine of the editor. Called while the console is set up
378 ;; for the editing. Returns edited string. Can bail out by an error.
379 ;; This routine may be reentered if SIGCONT happens.
380 (define (edit-main redisp)
381 (dynamic-wind
382 %sigcont-observe
383 (^[]
384 (ensure-bottom-room (~ ctx'console)) ; workaround for windows IME glitch
385 (when redisp (reset-terminal (~ ctx'console)))
386 (show-prompt ctx)
387 (init-screen-params ctx)
388 (edit-loop redisp #f))
389 %sigcont-unobserve))
390
391 ;;
392 ;; Main body
393 ;;
394 (reset-undo-info! ctx)
395 (reset-last-yank! ctx)
396 (let reenter ([refresh? #f])
397 (let1 r (guard (e [(and (<unhandled-signal-error> e)
398 (eqv? (~ e'signal) SIGINT))
399 (display "\nInput interrupted\n")
400 ""]
401 [(eq? e 'sigcont-received) e]
402 [else (raise e)])
403 (call-with-console (~ ctx'console) (^_ (edit-main refresh?))))
404 (if (eq? r 'sigcont-received)
405 (reenter #t)
406 r))))
407
408 ;; Check some parameters of screen.
409 (define (init-screen-params ctx)
410 (receive (y x) (query-cursor-position (~ ctx'console))
411 (set! (~ ctx'initpos-y) y)
412 (set! (~ ctx'lastpos-y) y)
413 (set! (~ ctx'initpos-x) x)
414 (set! (~ ctx'lastpos-x) x))
415 (reset-screen-size! ctx))
416
417 (define (reset-screen-size! ctx)
418 (receive (h w) (query-screen-size (~ ctx'console) #t)
419 (set! (~ ctx'screen-height) h)
420 (set! (~ ctx'screen-width) w)
421 (when (~ ctx'framebuffer)
422 (init-framebuffer (~ ctx'framebuffer) w h
423 (~ ctx'wide-char-pos-setting)))))
424
425 ;; If the cursor position has been moved from the supposed position,
426 ;; redisplay the prompt and reset initial position. This is called
427 ;; when something may be put on the screen and we don't want to
428 ;; clobber it.
429 (define (reset-cursor-pos ctx)
430 (receive (y x) (query-cursor-position (~ ctx'console))
431 (unless (and (= (~ ctx'lastpos-y) y)
432 (= (~ ctx'lastpos-x) x))
433 (move-cursor-to (~ ctx'console) y 0)
434 (show-prompt ctx)
435 (receive (y x) (query-cursor-position (~ ctx'console))
436 (set! (~ ctx'initpos-y) y)
437 (set! (~ ctx'initpos-x) x)))))
438
439 ;; Fetch next keystroke.
440 ;; Note: If we've received SIGCONT and the terminal has been turned back to
441 ;; the canonical mode, it is likely that we've stopped and then resumed
442 ;; by shell job control. The user may have tried several keystrokes, but
443 ;; they won't be sent to us until the user type Enter. We'll discard all
444 ;; those keys, then raises 'sigcont-received, which causes read-line/edit
445 ;; to reset the terminal mode and redisplay the buffer.
446 (define (next-keystroke ctx)
447 (define (call-timed-callback arg)
448 (and-let1 cb (~ ctx'timed-callback)
449 (set! (~ ctx'timed-callback) #f)
450 (cb arg)))
451 (if (queue-empty? (~ ctx'keystroke-queue))
452 (let1 ch (getch (~ ctx'console)
453 (and (~ ctx'timed-callback) 1.0e6)) ;1s timeout delay
454 (cond [(not ch) ;timeout
455 (call-timed-callback #f)
456 (next-keystroke ctx)]
457 [(and (%sigcont-received?)
458 (canonical-mode? (~ ctx'console)))
459 (let loop ()
460 (let1 ch (getch (~ ctx'console) 10000) ;10ms wait
461 (unless ch (raise 'sigcont-received))
462 (loop)))]
463 [else
464 (call-timed-callback ch)
465 ch]))
466 (queue-pop! (~ ctx'keystroke-queue))))
467
468 ;; Show prompt. Returns the current column.
469 (define (show-prompt ctx)
470 (let* ([p (~ ctx'prompt)]
471 [s (if (applicable? p) (with-output-to-string p) (x->string p))])
472 (putstr (~ ctx'console) s)))
473
474 ;; Show secondary prompt
475 ;; TODO: make this customizable
476 (define (show-secondary-prompt ctx)
477 (when (> (~ ctx'initpos-x) 0)
478 (putstr (~ ctx'console) (make-string (~ ctx'initpos-x) #\.))))
479
480 ;; Get a tab character width
481 (define (get-tab-char-width ctx x w)
482 (define tab-char-width (~ ctx'tab-char-width))
483 (min (- w x) (- tab-char-width (modulo x tab-char-width))))
484
485 (define (redisplay ctx buffer)
486 (if (~ ctx'framebuffer)
487 (let ([real-console (~ ctx'console)])
488 (set! (~ ctx'console) (~ ctx'framebuffer))
489 (%redisplay ctx buffer)
490 ;; maybe we should guard and reset ctx'console anyway to be safe...
491 (set! (~ ctx'console) real-console)
492 (draw-framebuffer (~ ctx'framebuffer) real-console (~ ctx'initpos-y) 0))
493 (%redisplay ctx buffer)))
494
495 (define (%redisplay ctx buffer)
496
497 ;; check a initial position
498 (when (< (~ ctx'initpos-y) 0)
499 (set! (~ ctx'initpos-y) 0))
500
501 (let* ([con (~ ctx'console)]
502 [y (~ ctx'initpos-y)]
503 [x (~ ctx'initpos-x)]
504 [w (~ ctx'screen-width)]
505 [h (~ ctx'screen-height)]
506 [sel (selected-range ctx buffer)]
507 [oldattr '(#f #f)]
508 [newattr '(#f #f)]
509 [disp-x x]
510 [g (gap-buffer->generator buffer)]
511 [pos (gap-buffer-pos buffer)]
512 [pos-x x]
513 [pos-y y]
514 [pos-set-flag (= pos 0)]
515 [maxy #f])
516
517 (define (display-area?)
518 (and (>= y 0) (or (not maxy) (<= y maxy))))
519
520 (define (line-wrapping disp-x1 w :optional (full-column-flag #f))
521 (when (>= disp-x1 w)
522 (set! x 0)
523 (set! disp-x 0)
524 (cond
525 [(display-area?)
526 (move-cursor-to con y 0)
527
528 ;; move cursor to the next line
529 (let1 dy (cursor-down/scroll-up con y h full-column-flag)
530 (set! y (+ y dy))
531 (set! (~ ctx'initpos-y) (+ (~ ctx'initpos-y) (- dy 1)))
532 (when pos-set-flag
533 (set! pos-y (+ pos-y (- dy 1)))
534 ;; check a cursor position for clipping a display area
535 (when (<= pos-y 0)
536 (set! pos-y 0)
537 (set! maxy (- h 2)))))]
538
539 [else
540 (inc! y)])))
541
542 (hide-cursor con)
543 (reset-character-attribute con)
544 (move-cursor-to con y 0)
545 (show-prompt ctx)
546 (clear-to-eos con)
547 (let loop ([n 0])
548 (glet1 ch (g)
549
550 ;; set character attributes
551 (set! newattr (current-char-attr n sel (~ ctx'paren-pos)))
552 (switch-char-attr-when-needed con oldattr newattr)
553 (set! oldattr newattr)
554
555 ;; display a character and do line wrapping
556 (case ch
557 [(#\newline)
558 (line-wrapping w w)
559 (when (display-area?)
560 (switch-char-attr-when-needed con newattr '(#f #f))
561 (show-secondary-prompt ctx)
562 (switch-char-attr-when-needed con '(#f #f) newattr))
563 (set! x (~ ctx'initpos-x))
564 (set! disp-x x)]
565 [(#\tab)
566 (let1 tw (get-tab-char-width ctx disp-x w)
567 (when (display-area?)
568 (move-cursor-to con y x)
569 (putstr con (make-string tw #\space)))
570 (set! x (+ x tw))
571 (set! disp-x (+ disp-x tw))
572 (line-wrapping disp-x w #t))]
573 [else
574 (let ([dw (get-char-width (~ ctx'wide-char-disp-setting) ch)]
575 [pw (get-char-width (~ ctx'wide-char-pos-setting) ch)])
576 ;; wide characters need a check of line wrapping before
577 ;; displaying them
578 (if (> dw 1) (line-wrapping (+ disp-x dw) (+ w 1)))
579 (when (display-area?)
580 (move-cursor-to con y x)
581 (putch con ch))
582 (set! x (+ x pw))
583 (set! disp-x (+ disp-x dw))
584 (line-wrapping disp-x w #t))])
585
586 ;; set a cursor position
587 (when (= pos (+ n 1))
588 (set! pos-set-flag #t)
589 (set! pos-x x)
590 (set! pos-y y))
591
592 (loop (+ n 1))))
593 (move-cursor-to con pos-y pos-x)
594 (set! (~ ctx'lastpos-y) pos-y)
595 (set! (~ ctx'lastpos-x) pos-x)
596 (show-cursor con)))
597
598 (define (current-char-attr pos sel oparen)
599 (cond-list
600 [#t @ '(#f #f)]
601 [(and sel (<= (car sel) pos) (< pos (cdr sel))) @ '(bright underscore)]
602 [(eqv? pos oparen) 'reverse]))
603
604 (define (switch-char-attr-when-needed con oldattr newattr)
605 (unless (equal? oldattr newattr)
606 (if (equal? newattr '(#f #f))
607 (reset-character-attribute con)
608 (set-character-attribute con newattr))))
609
610 ;; Show message at the starting point of the current input.
611 ;; MSG may be a string, or list of strings (lines).
612 ;; Redraw the current buffer below it.
613 ;; (Existing input is overwritten.)
614 (define (show-message ctx buffer msg :optional (attr #f))
615 (move-cursor-to (~ ctx'console) (~ ctx'initpos-y) 0)
616 (%draw-lines-with-attr ctx msg attr #t))
617
618 ;; Show message below the line where the cursor is at.
619 ;; Redraw the entire input after that.
620 (define (show-message-below ctx buffer msg :optional (attr #f))
621 (ensure-bottom-room (~ ctx'console))
622 (cursor-down/scroll-up (~ ctx'console))
623 (putch (~ ctx'console) #\return)
624 (%draw-lines-with-attr ctx msg attr #t))
625
626 (define (%draw-lines-with-attr ctx msg attr newline-after?)
627 (define lines
628 (cond [(string? msg) (string-split msg #\newline)]
629 [(list? msg) msg]
630 [else (error "[internal] string or list of strings required but got:"
631 msg)]))
632 (when attr
633 (set-character-attribute (~ ctx'console) attr))
634 (unwind-protect
635 (let loop ([lines lines])
636 (unless (null? lines)
637 (clear-to-eos (~ ctx'console))
638 (putstr (~ ctx'console) (car lines))
639 (when (or (pair? (cdr lines)) newline-after?)
640 (cursor-down/scroll-up (~ ctx'console))
641 (putch (~ ctx'console) #\return)
642 (ensure-bottom-room (~ ctx'console))
643 (when (< (~ ctx'initpos-y) (- (~ ctx'screen-height) 1))
644 (inc! (~ ctx'initpos-y))))
645 (loop (cdr lines))))
646 (when attr
647 (reset-character-attribute (~ ctx'console)))))
648
649 (define (ask-y-or-n ctx buffer msg)
650 (ensure-bottom-room (~ ctx'console))
651 (cursor-down/scroll-up (~ ctx'console))
652 (putch (~ ctx'console) #\return)
653 (%draw-lines-with-attr ctx #"~msg (y/n): " #f #f)
654 (or (eqv? #\y (getch (~ ctx'console)))
655 (begin
656 (cursor-down/scroll-up (~ ctx'console))
657 (putch (~ ctx'console) #\return)
658 (ensure-bottom-room (~ ctx'console))
659 (when (< (~ ctx'initpos-y) (- (~ ctx'screen-height) 1))
660 (inc! (~ ctx'initpos-y)))
661 #f)))
662
663 ;;
664 ;; Key combinations
665 ;;
666
667 (define (ctrl k)
668 (integer->char (- (logand (char->integer k) (lognot #x20)) #x40)))
669 (define (alt k) `(ALT ,k))
670
671 (define (macro! ctx . keys)
672 (apply enqueue! (~ ctx'keystroke-queue) keys)
673 'nop)
674
675 ;;
676 ;; Selection
677 ;;
678
679 (define (set-mark! ctx buffer)
680 (set! (~ ctx'marker-pos) (gap-buffer-pos buffer)))
681
682 (define (clear-mark! ctx buffer) (set! (~ ctx'marker-pos) #f))
683
684 (define (selected-range ctx buffer) ; returns (start . end), end exclusive
685 (and-let1 s (~ ctx'marker-pos)
686 (let1 p (gap-buffer-pos buffer)
687 (if (< p s) (cons p s) (cons s p)))))
688
689 ;;
690 ;; Undo stuff
691 ;;
692
693 (define (break-undo-sequence! ctx)
694 (unless (queue-empty? (~ ctx'redo-queue))
695 (apply queue-push! (~ ctx'undo-stack) (dequeue-all! (~ ctx'redo-queue)))))
696
697 (define (push-undo! ctx edit-command)
698 (queue-push! (~ ctx'undo-stack) edit-command))
699
700 (define (reset-undo-info! ctx)
701 (dequeue-all! (~ ctx'redo-queue))
702 (dequeue-all! (~ ctx'undo-stack)))
703
704 (define (set-undo-info! ctx undo-list)
705 (reset-undo-info! ctx)
706 (unless (null? undo-list)
707 (apply enqueue! (~ ctx'undo-stack) undo-list)))
708
709 ;;
710 ;; History
711 ;;
712
713 (define (duplicated-history? ctx str)
714 (and (not (ring-buffer-empty? (~ ctx'history)))
715 (string=? (ring-buffer-front (~ ctx'history)) str)))
716
717 ;; Enter the current buffer contents as the history, and discard any
718 ;; transient info. Returns the current buffer content.
719 (define (commit-history ctx buffer)
720 (rlet1 str (gap-buffer->string buffer)
721 (unless (or (string=? str "\n")
722 (string=? str "")
723 (duplicated-history? ctx str))
724 (ring-buffer-add-front! (~ ctx'history) str))
725 (set! (~ ctx'history-pos) -1)
726 (set! (~ ctx'history-transient) #f)))
727
728 ;; (~ ctx'history-transient) is a hashtable, indexed by history position
729 ;; (-1 being the fresh line), and its value is a pair of string and
730 ;; undo stack. When history is recalled and edited, and then the user
731 ;; moves history position, we save the edited line and its undo stack
732 ;; in this table. When the user comes back to the history position,
733 ;; we present the saved one instead of the actual history.
734 ;; Note that when the user recalls history for the first time of the session,
735 ;; we save the fresh line and its undo info in the transient table
736 ;; as the history position -1.
737 ;; The table is reset when the user commits the input.
738 (define (ensure-history-transient ctx)
739 (or (~ ctx'history-transient)
740 (rlet1 tab (make-hash-table 'eqv?)
741 (set! (~ ctx'history-transient) tab))))
742
743 ;; Save the current editing line to the transient table if necessary
744 (define (save-history-transient ctx buffer)
745 (break-undo-sequence! ctx) ; flush redo queue
746 (when (or (= (~ ctx'history-pos) -1)
747 (not (queue-empty? (~ ctx'undo-stack))))
748 (hash-table-put! (ensure-history-transient ctx)
749 (~ ctx'history-pos)
750 (cons (gap-buffer->string buffer)
751 (dequeue-all! (~ ctx'undo-stack))))))
752
753 ;; returns (<string> . <undo-list>)
754 (define (get-history ctx)
755 (let1 tab (ensure-history-transient ctx)
756 (or (hash-table-get tab (~ ctx'history-pos) #f)
757 (cons (ring-buffer-ref (~ ctx'history) (~ ctx'history-pos) "")
758 '()))))
759
760 (define (history-pos ctx) (~ ctx'history-pos))
761 (define (history-size ctx) (ring-buffer-num-entries (~ ctx'history)))
762
763 ;;
764 ;; Kill rings
765 ;;
766
767 (define (reset-last-yank! ctx)
768 (set! (~ ctx'last-yank) -1)
769 (set! (~ ctx'last-yank-pos) 0)
770 (set! (~ ctx'last-yank-size) 0))
771
772 (define (get-yank-line ctx)
773 (let* ([rb (~ ctx'kill-ring)]
774 [n (ring-buffer-num-entries rb)])
775 (if (zero? n)
776 "" ; no yank line
777 (ring-buffer-ref rb (modulo (~ ctx'last-yank) n)))))
778
779 (define (save-kill-ring ctx str)
780 (ring-buffer-add-front! (~ ctx'kill-ring) str))
781
782 (define (pop-yank-line ctx)
783 (if (zero? (ring-buffer-num-entries (~ ctx'kill-ring)))
784 ""
785 (begin (inc! (~ ctx'last-yank))
786 (get-yank-line ctx))))
787
788 ;;
789 ;; Some buffer utilities
790 ;;
791
792 (define (buffer-current-line&col buf)
793 (generator-fold (^[ch p]
794 (match-let1 (row . col) p
795 (if (eqv? ch #\newline)
796 (cons (+ row 1) 0)
797 (cons row (+ col 1)))))
798 '(0 . 0)
799 (gap-buffer->generator buf 0 (gap-buffer-pos buf))))
800
801 ;; returns the # of newline chars in buffer
802 (define (buffer-num-lines buf)
803 (generator-fold (^[ch cnt] (if (eqv? ch #\newline) (+ cnt 1) cnt))
804 0 (gap-buffer->generator buf)))
805
806 ;; Tries to set the buffer position in line & column. If the line
807 ;; isn't wide enough, set the position at the end of the line.
808 (define (buffer-set-line&col! buf line col)
809 (define nchars (gap-buffer-content-length buf))
810 (let skip-lines ([pos 0] [lin 0])
811 (cond [(= nchars pos) (gap-buffer-move! buf pos)]
812 [(= lin line)
813 (let skip-chars ([pos pos] [chr 0])
814 (if (or (= nchars pos)
815 (eqv? (gap-buffer-ref buf pos) #\newline)
816 (= chr col))
817 (gap-buffer-move! buf pos)
818 (skip-chars (+ pos 1) (+ chr 1))))]
819 [(eqv? (gap-buffer-ref buf pos) #\newline)
820 (skip-lines (+ pos 1) (+ lin 1))]
821 [else (skip-lines (+ pos 1) lin)])))
822
823 ;; Scan open paren from START, and when found, search matching close
824 ;; paren. When found, call found-fn with to indexes, the
825 ;; location of open paren and close paren.
826 ;; Returns (values <index-of-close-paren> <found-fn-result>).
827 ;; We'd scan recursively, but once found-fn returns a true value,
828 ;; we stop scanning and return those values to the top.
829 (define (buffer-scan-matching-parens buf start end found-fn)
830 (define parens '((#\( . #\)) (#\[ . #\]) (#\{ . #\})))
831 (define (scan i open-pos closer)
832 (if (= i end)
833 (values #f #f)
834 (let1 ch (gap-buffer-ref buf i)
835 (cond [(eqv? ch closer) (values i (found-fn open-pos i closer))]
836 [(eqv? ch #\\) (if (= i (- end 1))
837 (values #f #f)
838 (scan (+ i 2) open-pos closer))]
839 [(eqv? ch #\") (in-string (+ i 1) #\" open-pos closer)]
840 [(eqv? ch #\#)
841 (if (= i (- end 1))
842 (values #f #f)
843 (case (gap-buffer-ref buf (+ i 1))
844 [(#\" #\/) => (^c (in-string (+ i 2) c open-pos closer))]
845 [else (scan (+ i 1) open-pos closer)]))]
846 [(assq-ref parens ch) =>
847 (^[closer2]
848 (receive (close-pos result) (scan (+ i 1) i closer2)
849 (cond [result (values close-pos result)]
850 [close-pos (scan (+ close-pos 1) open-pos closer)]
851 [else (values #f #f)])))]
852 [else (scan (+ i 1) open-pos closer)]))))
853 (define (in-string i delim open-pos closer)
854 (if (= i end)
855 (values #f #f)
856 (let1 ch (gap-buffer-ref buf i)
857 (cond [(eqv? ch delim) (scan (+ i 1) open-pos closer)]
858 [(eqv? ch #\\) (if (= i (- end 1))
859 (values #f #f)
860 (in-string (+ i 2) delim open-pos closer))]
861 [else (in-string (+ i 1) delim open-pos closer)]))))
862 (scan start #f #f))
863
864 ;; Given closing paren position, find matching opening paren.
865 ;; START limits the search region (search performed between START and
866 ;; CURRENT-POS). The character at current-pos is used as the closer.
867 ;; Returns an index of matching opening paren, or #f.
868 (define (buffer-find-matching-paren buf start current-pos)
869 (receive (close-pos open-pos)
870 ($ buffer-scan-matching-parens buf start (+ current-pos 1)
871 (^[open-pos close-pos closer]
872 (and (eq? close-pos current-pos) ; found
873 open-pos)))
874 open-pos))
875
876 ;; Similar to above, but take the current cursor pos of the buffer.
877 (define (buffer-find-matching-paren-on-cursor buf)
878 (and (not (gap-buffer-gap-at? buf 'end))
879 (memv (gap-buffer-ref buf (gap-buffer-pos buf))
880 '(#\) #\] #\}))
881 (buffer-find-matching-paren buf 0 (gap-buffer-pos buf))))
882
883 ;; Pick word at the current position of BUF.
884 ;; Returns three values: The word, start position, and end position.
885 ;; The first word can be #f if the word isn't found.
886 ;; If the position doesn't have a word-constituent character, but
887 ;; the immediate left position has, then we pick the word immediately
888 ;; left on the position.
889 ;; This is mainly to extract a word to be used for completion. We don't
890 ;; do precise word segmentation (considering grapheme clusters); we just
891 ;; define 'word' as a consecutive characters in word-chars charset.
892 (define (buffer-find-word buf word-chars)
893 (define (scan-backward pos)
894 (cond [(= pos 0) 0]
895 [(word-chars (gap-buffer-ref buf (- pos 1))) (scan-backward (- pos 1))]
896 [else pos]))
897 (define (scan-forward pos)
898 (cond [(gap-buffer-pos-at-end? buf pos) pos]
899 [(word-chars (gap-buffer-ref buf pos)) (scan-forward (+ pos 1))]
900 [else pos]))
901
902 (let* ([pos (gap-buffer-pos buf)]
903 [start (scan-backward pos)]
904 [end (scan-forward pos)])
905 (values (if (= start end) #f (gap-buffer->string buf start end))
906 start
907 end)))
908
909 ;;;
910 ;;; Commands
911 ;;;
912
913 ;; Editor command, invoked by specific key sequence.
914 ;; Its handler is a procedure that takes <line-edit-context>,
915 ;; <gap-buffer>, and <key>.
916 ;; Return value indicates the action to be taken by the main editor
917 ;; loop. See the read-line/edit above for the details.
918
919 (define-class <edit-command> ()
920 ((name :init-keyword :name)
921 (handler :init-keyword :handler) ; handler
922 (docstring :init-keyword :docstring) ; document string
923
924 (all-commands :allocation :class
925 :init-form (make-hash-table 'eq?))
926 ))
927 (define-method initialize ((c <edit-command>) initargs)
928 (next-method)
929 (hash-table-put! (~ c'all-commands) (~ c'name) c))
930 (define-method object-apply ((c <edit-command>) ctx buf key)
931 ((~ c'handler) ctx buf key))
932
933 (define-syntax define-edit-command
934 (syntax-rules ()
935 [(_ (name . args) docstring . body)
936 (define name (make <edit-command>
937 :name 'name
938 :handler (^ args . body)
939 :docstring docstring))]))
940
941
942 (define-edit-command (self-insert-command ctx buf key)
943 "Insert typed character at the cursor, and position the cursor after it."
944 (reset-last-yank! ctx)
945 (break-undo-sequence! ctx)
946 (clear-mark! ctx buf)
947 (gap-buffer-edit! buf `(i #f ,(x->string key))))
948
949 (define-edit-command (quoted-insert ctx buf key)
950 "Read next keystroke and insert it into the buffer at the cursor."
951 (let1 ch (next-keystroke ctx) ; TODO: octal digits input
952 (gap-buffer-edit! buf `(i #f ,(x->string ch)))))
953
954 (define-edit-command (insert-closing-paren ctx buf key)
955 "Insert closing paren, and highlight corresponding opening paren."
956 (reset-last-yank! ctx)
957 (break-undo-sequence! ctx)
958 (clear-mark! ctx buf)
959 (begin0
960 (gap-buffer-edit! buf `(i #f ")"))
961 (let1 open-pos (buffer-find-matching-paren buf 0 (- (gap-buffer-pos buf) 1))
962 (set! (~ ctx'paren-pos) open-pos)
963 (set! (~ ctx'timed-callback)
964 (^_ (set! (~ ctx'paren-pos) #f)
965 (redisplay ctx buf))))))
966
967 (define-edit-command (insert-parentheses ctx buf key)
968 "Insert a pair of parentheses at the cursor, and position the cursor \
969 between them."
970 (macro! ctx #\( #\) (ctrl #\b)))
971
972 (define-edit-command (commit-input ctx buf key)
973 "Commit the current buffer content as the finished input."
974 'commit)
975
976 (define-edit-command (commit-or-newline ctx buf key)
977 "If the current buffer content consists a complete input, \
978 commit it as the finished input. Otherwise, insert a newline."
979 (or (and-let* ([pred (~ ctx'input-continues)]
980 [ (pred (gap-buffer->string buf)) ])
981 (gap-buffer-edit! buf '(i #f "\n")))
982 'commit))
983
984 (define-edit-command (delete-char ctx buf key)
985 "Delete a single character at the cursor. \
986 If the cursor is at the end of the buffer, do nothing."
987 (if (not (gap-buffer-gap-at? buf 'end))
988 (gap-buffer-edit! buf '(d #f 1))
989 'unchanged))
990
991 (define-edit-command (eot-or-delete-char ctx buf key)
992 "If the buffer is empty, commit input as EOF. Otherwise, delete \
993 one character at the cursor."
994 (if (zero? (gap-buffer-content-length buf))
995 (eof-object)
996 (delete-char ctx buf key)))
997
998 (define-edit-command (delete-backward-char ctx buf key)
999 "Delete one character right before the cursor. \
1000 If the current point is beginning of the buffer, do nothing."
1001 (if (not (gap-buffer-gap-at? buf 'beginning))
1002 (let1 p-1 (- (gap-buffer-pos buf) 1)
1003 (gap-buffer-edit! buf `(d ,p-1 1)))
1004 'unchanged))
1005
1006 (define-edit-command (backward-char ctx buf key)
1007 "Move the cursor one character backward. If the cursor is at the beginning, \
1008 do nothing."
1009 (if (not (gap-buffer-gap-at? buf 'beginning))
1010 (begin (gap-buffer-move! buf -1 'current)
1011 'moved)
1012 'unchanged))
1013
1014 (define-edit-command (forward-char ctx buf key)
1015 "Move the cursor one character forward. If the cursor is at the end of the \
1016 buffer, do nothing."
1017 (if (not (gap-buffer-gap-at? buf 'end))
1018 (begin (gap-buffer-move! buf 1 'current)
1019 'moved)
1020 'unchanged))
1021
1022 (define (move-word! buf move-offset cset peek-offset)
1023 (let loop ([result #f])
1024 (cond
1025 [(gap-buffer-gap-at? buf (if (negative? move-offset) 'beginning 'end))
1026 result]
1027 [(char-set-contains? cset
1028 (gap-buffer-ref buf
1029 (+ (gap-buffer-pos buf) peek-offset)
1030 #\space))
1031 (begin
1032 (gap-buffer-move! buf move-offset 'current)
1033 (loop #t))]
1034 [else
1035 result])))
1036
1037 (define-edit-command (backward-word ctx buf key)
1038 "Move the cursor one word backward."
1039 (let* ([res1 (move-word! buf -1 #[\W] -1)]
1040 [res2 (move-word! buf -1 #[\w] -1)])
1041 (if (or res1 res2) 'moved 'unchanged)))
1042
1043 (define-edit-command (forward-word ctx buf key)
1044 "Move the cursor one word forward."
1045 (let* ([res1 (move-word! buf 1 #[\W] 0)]
1046 [res2 (move-word! buf 1 #[\w] 0)])
1047 (if (or res1 res2) 'moved 'unchanged)))
1048
1049 (define-edit-command (move-beginning-of-buffer ctx buf key)
1050 "Position the cursor at the beginning of the buffer."
1051 (if (not (gap-buffer-gap-at? buf 'beginning))
1052 (begin (gap-buffer-move! buf 0 'beginning)
1053 'moved)
1054 'unchanged))
1055
1056 (define-edit-command (move-end-of-buffer ctx buf key)
1057 "Position the cursor at the end of the buffer."
1058 (if (not (gap-buffer-gap-at? buf 'end))
1059 (begin (gap-buffer-move! buf 0 'end)
1060 'moved)
1061 'unchanged))
1062
1063 (define-edit-command (move-beginning-of-line ctx buf key)
1064 "Move the cursor at the beginning of the current line."
1065 (match-let1 (lines . col) (buffer-current-line&col buf)
1066 (if (zero? col)
1067 'unchanged
1068 (begin
1069 (buffer-set-line&col! buf lines 0)
1070 'moved))))
1071
1072 (define-edit-command (move-end-of-line ctx buf key)
1073 "Move the cursor at the end of the current line."
1074 (match-let1 (lines . col) (buffer-current-line&col buf)
1075 (buffer-set-line&col! buf lines 9999)
1076 'moved))
1077
1078 (define-edit-command (set-mark-command ctx buf key)
1079 "Set mark at the current cursor position."
1080 (set-mark! ctx buf)
1081 'moved)
1082
1083 (define-edit-command (kill-line ctx buf key)
1084 "If the cursor is at the end of line, delete the newline character and \
1085 combine the line with the next line. Otherwise, delete characters from \
1086 the cursor to the end of the line."
1087 (cond
1088 [(gap-buffer-gap-at? buf 'end)
1089 'unchanged]
1090 [(eqv? (gap-buffer-ref buf (gap-buffer-pos buf)) #\newline)
1091 (macro! ctx (ctrl #\d))]
1092 [else
1093 (macro! ctx (ctrl #\@) (ctrl #\e) (ctrl #\w))]))
1094
1095 (define-edit-command (kill-region ctx buf key)
1096 "Delete characters between the cursor and the mark, and save them into \
1097 the kill ring. If there's no active mark, do nothing."
1098 (match (selected-range ctx buf)
1099 [(start . end)
1100 ;; NB: the cursor is either on start or on end. either way,
1101 ;; after operation the cursor's be at start.
1102 (rlet1 e (gap-buffer-edit! buf `(d ,start ,(- end start)))
1103 ;; e contains (i <pos> <killed-string>)
1104 (save-kill-ring ctx (caddr e)))]
1105 [_ 'unchanged]))
1106
1107 (define-edit-command (kill-ring-save ctx buf key)
1108 "Save the characters between the cursor and the mark into the kill-ring. \
1109 The contents of the buffer isn't changed, but the mark is cleared."
1110 (match (selected-range ctx buf)
1111 [(start . end)
1112 (save-kill-ring ctx (gap-buffer->string buf start end))
1113 'visible] ; this clears selection
1114 [_ 'unchanged]))
1115
1116 (define-edit-command (kill-word ctx buf key)
1117 "Delete characters from the cursor to the end of the word, and save them \
1118 into the kill ring. The mark is cleared."
1119 (macro! ctx (ctrl #\@) (alt #\f) (ctrl #\w)))
1120
1121 (define-edit-command (backward-kill-word ctx buf key)
1122 "Delete characters from the cursor to the beginning of the word, and save \
1123 them into the kill ring. The mark is cleared."
1124 (macro! ctx (ctrl #\@) (alt #\b) (ctrl #\w)))
1125
1126 (define-edit-command (refresh-display ctx buf key)
1127 "Redraw contents of the buffer."
1128 (reset-terminal (~ ctx'console))
1129 (reset-screen-size! ctx)
1130 (move-cursor-to (~ ctx'console) 0 0) ;redundant, but mintty has problem without this
1131 (show-prompt ctx)
1132 (init-screen-params ctx)
1133 'visible)
1134
1135 ;; NB: This command may modify undo queue
1136 (define-edit-command (prev-history ctx buf key)
1137 "Replace the buffer content with the last item in the history currently \
1138 looking at."
1139 (if (< (history-pos ctx) (- (history-size ctx) 1))
1140 (begin
1141 (save-history-transient ctx buf)
1142 (inc! (~ ctx'history-pos))
1143 (let1 p (get-history ctx)
1144 (set-undo-info! ctx (cdr p))
1145 (gap-buffer-clear! buf)
1146 (gap-buffer-insert! buf (car p))
1147 'visible))
1148 'unchanged))
1149
1150 ;; NB: This command may modify undo queue
1151 (define-edit-command (next-history ctx buf key)
1152 "Replace the buffer content with the next item in the history currently \
1153 looking at."
1154 (if (> (history-pos ctx) -1)
1155 (begin
1156 (save-history-transient ctx buf)
1157 (dec! (~ ctx'history-pos))
1158 (let1 p (get-history ctx)
1159 (set-undo-info! ctx (cdr p))
1160 (gap-buffer-clear! buf)
1161 (gap-buffer-insert! buf (car p))
1162 'visible))
1163 'unchanged))
1164
1165 (define-edit-command (prev-line-or-history ctx buf key)
1166 "If the cursor is at the first line, do prev-sitory. Otherwise, \
1167 move the cursor one line up."
1168 (match-let1 (lines . col) (buffer-current-line&col buf)
1169 (if (zero? lines)
1170 (prev-history ctx buf key)
1171 (begin (buffer-set-line&col! buf (- lines 1) col) 'moved))))
1172
1173 (define-edit-command (next-line-or-history ctx buf key)
1174 "If the cursor is at the last line, do next-sitory. Otherwise, \
1175 move the cursor one line down."
1176 (match-let1 (lines . col) (buffer-current-line&col buf)
1177 (if (= lines (buffer-num-lines buf))
1178 (next-history ctx buf key)
1179 (begin (buffer-set-line&col! buf (+ lines 1) col) 'moved))))
1180
1181
1182 (define-edit-command (transpose-chars ctx buf key)
1183 "Exchange characters on the cursor and before the cursor and position \
1184 the cursor one character before. If the buffer is empty, do nothing. \
1185 If the buffer has only one character, just move the cursor."
1186 (cond [(gap-buffer-gap-at? buf 'beginning) 'unchanged]
1187 [(= (gap-buffer-content-length buf) 1) ; special case
1188 (gap-buffer-move! buf 0)
1189 'moved]
1190 [else
1191 (gap-buffer-move! buf
1192 (if (gap-buffer-gap-at? buf 'end) -2 -1)
1193 'current)
1194 (let ([cur (gap-buffer-ref buf (+ (gap-buffer-pos buf) 1))]
1195 [prev (gap-buffer-ref buf (gap-buffer-pos buf))])
1196 (gap-buffer-edit! buf `(c #f 2 ,(string cur prev))))]))
1197
1198 (define-edit-command (yank ctx buf key)
1199 "Insert the last chunk in the kill ring at the cursor \
1200 position."
1201 (if (> (ring-buffer-num-entries (~ ctx'kill-ring)) 0)
1202 (begin
1203 (set! (~ ctx'last-yank) 0)
1204 (set! (~ ctx'last-yank-pos) (gap-buffer-pos buf))
1205 (let1 yanked-text (get-yank-line ctx)
1206 (set! (~ ctx'last-yank-size) (string-length yanked-text))
1207 `(yanked ,(gap-buffer-edit! buf `(i #f ,yanked-text)))))
1208 'unchanged))
1209
1210 (define-edit-command (yank-pop ctx buf key)
1211 "Replace just yanked chunk of characters with the other chunk in the kill \
1212 ring."
1213 (if (and (> (ring-buffer-num-entries (~ ctx'kill-ring)) 0)
1214 (>= (~ ctx'last-yank) 0))
1215 (let* ([text (pop-yank-line ctx)]
1216 [pos (~ ctx'last-yank-pos)]
1217 [len (~ ctx'last-yank-size)]
1218 [edit (gap-buffer-edit! buf `(c ,pos ,len ,text))])
1219 (set! (~ ctx'last-yank-size) (string-length text))
1220 `(yanked ,edit))
1221 'unchanged))
1222
1223 (define-edit-command (undo ctx buf key)
1224 "Undo the last change."
1225 (if (not (queue-empty? (~ ctx'undo-stack)))
1226 (let* ([undo-command (queue-pop! (~ ctx'undo-stack))]
1227 [redo-command (gap-buffer-edit! buf undo-command)])
1228 (queue-push! (~ ctx'redo-queue) undo-command)
1229 (enqueue! (~ ctx'redo-queue) redo-command)
1230 'undone)
1231 'unchanged))
1232
1233 (define-edit-command (keyboard-quit ctx buf key)
1234 "Reset yank sequence, clear a mark, and break undo sequence. Basically, \
1235 break whatever work that spans for several commands."
1236 (beep (~ ctx'console))
1237 'visible)
1238
1239 (define-edit-command (edit-with-editor ctx buf key)
1240 "Edit the current input buffer with the external editor"
1241 (let* ([orig (gap-buffer->string buf)]
1242 [edited (ed-string orig)])
1243 (cond
1244 [(not edited)
1245 (show-message ctx buf "External editor is not available."
1246 '(#f #f reverse))
1247 'redraw]
1248 [(equal? orig edited)
1249 'unchanged]
1250 [else
1251 (gap-buffer-clear! buf)
1252 (gap-buffer-insert! buf edited)
1253 'visible])))
1254
1255 (define-edit-command (undefined-command ctx buf key)
1256 "Placeholder for a keystroke that isn't assigned to any command."
1257 (beep (~ ctx'console))
1258 (show-message ctx buf
1259 #"Unknown keystroke ~(keys->string '() key). \
1260 Type M-h b for the list of key bindings."
1261 '(#f #f reverse))
1262 'redraw)
1263
1264 (define-edit-command (undefined-or-self-insert-command ctx buf key)
1265 "Insert the key if its a character beyond ascii range, otherwise behave \
1266 as the undefined command."
1267 (if (and (char? key)
1268 (> (char->integer key) #x7f))
1269 (self-insert-command ctx buf key)
1270 (undefined-command ctx buf key)))
1271
1272 (define-edit-command (nop-command ctx buf key)
1273 "Do nothing."
1274 'nop)
1275
1276 (define-edit-command (completion-command ctx buf key)
1277 "Try to complete the (partial) word at the cursor."
1278 (receive (word start-pos end-pos)
1279 (buffer-find-word buf (~ ctx'completion-word-constituent?))
1280 (or (and-let* ([ word ]
1281 [lister (~ ctx'completion-lister)]
1282 [words (lister word buf start-pos end-pos)])
1283 (match words
1284 [() #f]
1285 [(? string?)
1286 ;; Final candidate. We append whitespace after it.
1287 (gap-buffer-move! buf start-pos)
1288 (gap-buffer-replace! buf (- end-pos start-pos) #"~|words| ")
1289 'redraw]
1290 [(w)
1291 ;; Single candidate, but may be completed further.
1292 (gap-buffer-move! buf start-pos)
1293 (gap-buffer-replace! buf (- end-pos start-pos) w)
1294 'redraw]
1295 [(w ws ...)
1296 (when (eq? (~ ctx'last-command) completion-command)
1297 ;; We split string for..
1298 ;; - Output of display-multicolumn contains newline at the
1299 ;; end. We don't want to display it.
1300 ;; - We need to know # of rows to switch how to display it
1301 (let1 candidates (string-split
1302 (with-output-to-string
1303 (cut display-multicolumn (cons w ws)
1304 :width (~ ctx'screen-width)))
1305 #\newline 'suffix)
1306 (if (length<? candidates 20)
1307 (show-message-below ctx buf candidates)
1308 (if ($ ask-y-or-n ctx buf
1309 $ format "Display all ~d possibilities?"
1310 $ + 1 (length ws))
1311 (display/pager (string-join candidates "\n"))))))
1312 ;; Replace input with the longest common prefix. This allows
1313 ;; to complete 'defi' to 'define', while continuing the input.
1314 ;; Note that if segmented match is used, common prefix can
1315 ;; be shorter than the current input; e.g. 'c-w' lists candidates
1316 ;; such as 'call-with-values' and 'char-word-consituent?', and
1317 ;; the common prefix is 'c'. In such case we leave the current
1318 ;; input.
1319 (let1 pre (fold common-prefix w ws)
1320 (when (> (string-length pre) (- end-pos start-pos))
1321 (gap-buffer-move! buf start-pos)
1322 (gap-buffer-replace! buf (- end-pos start-pos) pre))
1323 'redraw)]))
1324 'nop)))
1325
1326 (define-edit-command (help-binding-command ctx buf key)
1327 "Show key bindings."
1328 (display/pager
1329 (with-output-to-string
1330 (^[] (print "Line editor key bindings:") (print)
1331 (keymap-describe-recursively (~ ctx'keymap)))))
1332 'redraw)
1333
1334 (define-edit-command (help-summary-command ctx buf key)
1335 "General help string"
1336 (let ((dkm (default-keymap)))
1337 (define (lookup name)
1338 (command-name->keystroke-string dkm name))
1339 (define Help-b (lookup 'help-binding-command))
1340 (define Help-k (lookup 'help-keystroke-command))
1341 (define C-f (lookup 'forward-char))
1342 (define C-b (lookup 'backward-char))
1343 (define C-p (lookup 'prev-line-or-history))
1344 (define C-n (lookup 'next-line-or-history))
1345 (define C-a (lookup 'move-beginning-of-line))
1346 (define C-e (lookup 'move-end-of-line))
1347 (define M-f (lookup 'forward-word))
1348 (define M-b (lookup 'backward-word))
1349 (define M-p (lookup 'prev-history))
1350 (define M-n (lookup 'next-history))
1351 (define M-< (lookup 'move-beginning-of-buffer))
1352 (define M-> (lookup 'move-end-of-buffer))
1353 (define C-@ (lookup 'set-mark-command))
1354 (define C-w (lookup 'kill-region))
1355 (define C-k (lookup 'kill-line))
1356 (define M-d (lookup 'kill-word))
1357 (define C-y (lookup 'yank))
1358 (define M-y (lookup 'yank-pop))
1359 (define C-_ (lookup 'undo))
1360 (define M-C-x (lookup 'commit-input))
1361 (define C-l (lookup 'refresh-display))
1362
1363 (display/pager
1364 #"\
1365 Gauche input editing quick cheat sheet:
1366 ~Help-b for keymap
1367 ~Help-k <keystroke> ... for help of specific keystroke
1368
1369 ~|C-f|/~C-b forward/backward char ~|M-f|/~M-b forward/backward word
1370 ~|C-p|/~C-n prev/next line or history ~|M-p|/~M-n prev/next history
1371 ~|C-a|/~C-e beginning/end line ~|M-<|/~M-> beginning/end buffer
1372 ~|C-@| mark ~|C-w| kill region
1373 ~|C-k| kill line ~|M-d| kill word
1374 ~|C-y| yank ~|M-y| yank pop
1375 ~|C-_| undo ~|M-C-x| commit input
1376 ~|C-l| refresh disiplay
1377 To disable input editing: Type ,edit off")
1378 'redraw))
1379
1380 (define-edit-command (help-keystroke-command ctx buf key)
1381 "Show description of given keystroke(s)."
1382 (let loop ([ch (next-keystroke ctx)]
1383 [keymap (~ ctx'keymap)]
1384 [keystrokes '()])
1385 (let1 h (keymap-ref keymap ch)
1386 (cond [(is-a? h <edit-command>)
1387 (let1 msg (format "~22a ~a\n~a"
1388 (keys->string (reverse keystrokes) ch)
1389 (~ h'name)
1390 (~ h'docstring))
1391 (show-message ctx buf msg '(#f #f bright)))]
1392 [(is-a? h <keymap>)
1393 (loop (next-keystroke ctx) h (cons ch keystrokes))]
1394 [else #f]))) ;can't happen, but just ignore
1395 'redraw)
1396
1397 ;;;
1398 ;;; Keymaps
1399 ;;;
1400
1401 ;; Keymap maps a keystroke (either <char> or (ALT <char>))
1402 ;; to a command or another keymap.
1403 (define-class <keymap> ()
1404 ((name :init-keyword :name)
1405 (table :init-keyword :table) ;hashtable
1406 (default :init-keyword :default)))
1407
1408 ;; Stacked keymap is like <keymap>, except that default slot is
1409 ;; always a <keymap>, and if a keystroke is not in the table,
1410 ;; lookup is delegated to that keymap.
1411 ;; (It is distinguished from a <keymap> whose default value is
1412 ;; a secondary keymap - in that case, a keystroke falls on the default
1413 ;; replaces the current keymap to it.)
1414 (define-class <stacked-keymap> (<keymap>) ())
1415
1416 (define (make-keymap :optional (name #f) (default undefined-command))
1417 (make <keymap> :name name :table (make-hash-table 'equal?) :default default))
1418
1419 (define (make-stacked-keymap base-keymap :optional (name #f))
1420 (make <stacked-keymap> :name name :table (make-hash-table 'equal?)
1421 :default base-keymap))
1422
1423 (define (copy-keymap km :optional (name #f))
1424 (make (class-of km)
1425 :name name
1426 :table (hash-table-copy (~ km'table))
1427 :default (~ km'default)))
1428
1429 (define-method keymap-ref ((km <keymap>) keystroke)
1430 (or (hash-table-get (~ km'table) keystroke #f)
1431 (~ km'default)))
1432
1433 (define-method keymap-ref ((km <stacked-keymap>) keystroke)
1434 (or (hash-table-ref (~ km'table) keystroke #f)
1435 (keymap-ref (~ km'default) keystroke)))
1436
1437 (define (command-name->keystrokes km command-name)
1438 (assume-type km <keymap>)
1439 (assume-type command-name <symbol>)
1440 (letrec ([pred (^[km k v]
1441 (cond [(is-a? v <keymap>)
1442 (and-let1 r (pick v)
1443 (cons k r))]
1444 [(is-a? v <edit-command>)
1445 (and (eq? command-name (~ v'name))
1446 (list k))]
1447 [else (error "Broken keymap:" km)]))]
1448 [pick (^[km]
1449 ;; NB: We take precedence in ordinary keys to special keys
1450 (or ($ hash-table-find (~ km'table)
1451 (^[k v] (and (not (symbol? k)) (pred km k v))))
1452 ($ hash-table-find (~ km'table)
1453 (^[k v] (and (symbol? k) (pred km k v))))))])
1454 (pick km)))
1455
1456 (define (command-name->keystroke-string km command-name)
1457 (and-let1 ks (command-name->keystrokes km command-name)
1458 (let1 s (keys->string ks #f)
1459 (substring s 0 (- (string-length s) 1))))) ;avoid depending SRFI-13
1460
1461 (define-syntax define-key
1462 (syntax-rules ()
1463 [(_ km keystroke command)
1464 (hash-table-put! (~ km'table) keystroke command)]))
1465
1466 (define (keys->string prefixes key)
1467 (define (key->string k)
1468 (match k
1469 [('ALT x) #"M-~(key->string x)"]
1470 [(? symbol?) (x->string k)]
1471 [#\space "SPC"]
1472 [#\del "DEL"]
1473 [_ (cond
1474 [(char=? k #\null) "C-@"]
1475 [(char<=? k #\x1a) #"C-~(integer->char (+ (char->integer k) 96))"]
1476 [(char<? k #\space) #"C-~(integer->char (+ (char->integer k) 64))"]
1477 [else (string k)])]))
1478 (string-append (if (null? prefixes)
1479 ""
1480 (string-join (map (cut keys->string '() <>) prefixes)
1481 " " 'suffix))
1482 (if key
1483 (key->string key)
1484 "")))
1485
1486 (define (keymap-describe km :optional (prefix-keys '()))
1487 (define (show-key k)
1488 (match k
1489 [('ALT x) #"M-~(show-key x)"]
1490 [(? symbol?) (x->string k)]
1491 [#\space "SPC"]
1492 [#\del "DEL"]
1493 [_ (cond
1494 [(char=? k #\null) "C-@"]
1495 [(char<=? k #\x1a) #"C-~(integer->char (+ (char->integer k) 96))"]
1496 [(char<? k #\space) #"C-~(integer->char (+ (char->integer k) 64))"]
1497 [else (string k)])]))
1498 (define (key<? x y)
1499 (match x
1500 [('ALT xx)
1501 (match y
1502 [('ALT yy) (key<? xx yy)]
1503 [_ #f])]
1504 [(? symbol?)
1505 (match y
1506 [('ALT _) #t]
1507 [(? symbol?) (<? default-comparator x y)]
1508 [_ #f])]
1509 [_ (if (char? y)
1510 (char<? x y)
1511 #t)]))
1512 (define (show-value v)
1513 (cond [(is-a? v <edit-command>) (~ v'name)]
1514 [(is-a? v <keymap>) (or #"(~(~ v'name))"
1515 "(anonymous keymap)")]
1516 [else v])) ;shouldn't happen
1517 (define (show-entry-1 k v)
1518 (format #t " ~20a ~a\n" (keys->string prefix-keys k) (show-value v)))
1519 (define (show-entry-n k0 k1 v)
1520 (when k0
1521 (if (equal? k0 k1)
1522 (show-entry-1 k0 v)
1523 (format #t " ~20a ~a\n"
1524 #"~(keys->string prefix-keys k0) .. ~(keys->string '() k1)"
1525 (show-value v)))))
1526 (let loop ([ks (sort (hash-table-keys (~ km'table)) key<?)]
1527 [group-start #f]
1528 [group-end #f])
1529 (if (null? ks)
1530 (show-entry-n group-start group-end self-insert-command)
1531 (let1 v (hash-table-get (~ km'table) (car ks))
1532 (if (eq? v self-insert-command)
1533 (loop (cdr ks) (or group-start (car ks)) (car ks))
1534 (begin
1535 (show-entry-n group-start group-end self-insert-command)
1536 (show-entry-1 (car ks) v)
1537 (loop (cdr ks) #f #f)))))))
1538
1539 (define (keymap-describe-recursively km)
1540 (define (rec km prefixes)
1541 (print (or (~ km'name) "(anonymous keymap)"))
1542 (keymap-describe km prefixes)
1543 (hash-table-for-each
1544 (~ km'table)
1545 (^[k v] (when (is-a? v <keymap>)
1546 (print)
1547 (rec v (append prefixes (list k)))))))
1548 (rec km '()))
1549
1550 ;; M-h - help keymap
1551 (define *help-keymap* (make-keymap "Help keymap"))
1552
1553 (define-key *help-keymap* #\b help-binding-command)
1554 (define-key *help-keymap* #\h help-summary-command)
1555 (define-key *help-keymap* #\k help-keystroke-command)
1556
1557 ;; C-x - general prefix
1558 (define *c-x-keymap* (make-keymap "C-x prefix"))
1559
1560 (define-key *c-x-keymap* #\e edit-with-editor)
1561
1562 ;; Default keymap.
1563 (define *default-keymap* (make-keymap "Default keymap"
1564 undefined-or-self-insert-command))
1565
1566 (define-key *default-keymap* (ctrl #\@) set-mark-command)
1567 (define-key *default-keymap* (ctrl #\a) move-beginning-of-line)
1568 (define-key *default-keymap* (ctrl #\b) backward-char)
1569 ;;(define-key *default-keymap* (ctrl #\c) undefined-command)
1570 (define-key *default-keymap* (ctrl #\d) eot-or-delete-char)
1571 (define-key *default-keymap* (ctrl #\e) move-end-of-line)
1572 (define-key *default-keymap* (ctrl #\f) forward-char)
1573 (define-key *default-keymap* (ctrl #\g) keyboard-quit)
1574 (define-key *default-keymap* (ctrl #\h) delete-backward-char)
1575 (define-key *default-keymap* (ctrl #\i) completion-command) ; tab
1576 (define-key *default-keymap* (ctrl #\j) self-insert-command) ; newline
1577 (define-key *default-keymap* (ctrl #\k) kill-line)
1578 (define-key *default-keymap* (ctrl #\l) refresh-display)
1579 (define-key *default-keymap* (ctrl #\m) commit-or-newline) ; return
1580 (define-key *default-keymap* (ctrl #\n) next-line-or-history)
1581 ;;(define-key *default-keymap* (ctrl #\o) undefined-command)
1582 (define-key *default-keymap* (ctrl #\p) prev-line-or-history)
1583 (define-key *default-keymap* (ctrl #\q) quoted-insert)
1584 ;;(define-key *default-keymap* (ctrl #\r) undefined-command)
1585 ;;(define-key *default-keymap* (ctrl #\s) undefined-command)
1586 (define-key *default-keymap* (ctrl #\t) transpose-chars)
1587 ;;(define-key *default-keymap* (ctrl #\u) undefined-command)
1588 ;;(define-key *default-keymap* (ctrl #\v) undefined-command)
1589 (define-key *default-keymap* (ctrl #\w) kill-region)
1590 (define-key *default-keymap* (ctrl #\x) *c-x-keymap*)
1591 (define-key *default-keymap* (ctrl #\y) yank)
1592 ;;(define-key *default-keymap* (ctrl #\z) undefined-command)
1593 ;;(define-key *default-keymap* (ctrl #\[) undefined-command)
1594 ;;(define-key *default-keymap* (ctrl #\\) undefined-command)
1595 ;;(define-key *default-keymap* (ctrl #\]) undefined-command)
1596 ;;(define-key *default-keymap* (ctrl #\^) undefined-command)
1597 (define-key *default-keymap* (ctrl #\_) undo)
1598
1599 (do ([c #x20 (+ c 1)])
1600 [(= c #x7f)]
1601 (unless (= c #x29) ;close paren
1602 (define-key *default-keymap* (integer->char c) self-insert-command)))
1603
1604 (define-key *default-keymap* #\) insert-closing-paren)
1605
1606 (define-key *default-keymap* (alt #\null) nop-command) ; for windows (ime on/off)
1607 ;;(define-key *default-keymap* (alt #\space) undefined-command) ; should be set-mark
1608 ;;(define-key *default-keymap* (alt #\!) undefined-command)
1609 ;;(define-key *default-keymap* (alt #\") undefined-command)
1610 ;;(define-key *default-keymap* (alt #\#) undefined-command)
1611 ;;(define-key *default-keymap* (alt #\$) undefined-command)
1612 ;;(define-key *default-keymap* (alt #\%) undefined-command)
1613 ;;(define-key *default-keymap* (alt #\&) undefined-command)
1614 ;;(define-key *default-keymap* (alt #\') undefined-command)
1615 (define-key *default-keymap* (alt #\() insert-parentheses)
1616 ;;(define-key *default-keymap* (alt #\)) undefined-command)
1617 ;;(define-key *default-keymap* (alt #\*) undefined-command)
1618 ;;(define-key *default-keymap* (alt #\+) undefined-command)
1619 ;;(define-key *default-keymap* (alt #\,) undefined-command)
1620 ;;(define-key *default-keymap* (alt #\-) undefined-command)
1621 ;;(define-key *default-keymap* (alt #\.) undefined-command)
1622 ;;(define-key *default-keymap* (alt #\/) undefined-command)
1623 ;;(define-key *default-keymap* (alt #\0) undefined-command)
1624 ;;(define-key *default-keymap* (alt #\1) undefined-command)
1625 ;;(define-key *default-keymap* (alt #\2) undefined-command)
1626 ;;(define-key *default-keymap* (alt #\3) undefined-command)
1627 ;;(define-key *default-keymap* (alt #\4) undefined-command)
1628 ;;(define-key *default-keymap* (alt #\5) undefined-command)
1629 ;;(define-key *default-keymap* (alt #\6) undefined-command)
1630 ;;(define-key *default-keymap* (alt #\7) undefined-command)
1631 ;;(define-key *default-keymap* (alt #\8) undefined-command)
1632 ;;(define-key *default-keymap* (alt #\9) undefined-command)
1633 ;;(define-key *default-keymap* (alt #\:) undefined-command)
1634 ;;(define-key *default-keymap* (alt #\;) undefined-command)
1635 (define-key *default-keymap* (alt #\<) move-beginning-of-buffer)
1636 ;;(define-key *default-keymap* (alt #\=) undefined-command)
1637 (define-key *default-keymap* (alt #\>) move-end-of-buffer)
1638 ;;(define-key *default-keymap* (alt #\?) undefined-command)
1639
1640
1641 ;;(define-key *default-keymap* (alt #\@) undefined-command)
1642 ;;(define-key *default-keymap* (alt #\A) undefined-command)
1643 ;;(define-key *default-keymap* (alt #\B) undefined-command)
1644 ;;(define-key *default-keymap* (alt #\C) undefined-command)
1645 ;;(define-key *default-keymap* (alt #\D) undefined-command)
1646 ;;(define-key *default-keymap* (alt #\E) undefined-command)
1647 ;;(define-key *default-keymap* (alt #\F) undefined-command)
1648 ;;(define-key *default-keymap* (alt #\G) undefined-command)
1649 ;;(define-key *default-keymap* (alt #\H) undefined-command)
1650 ;;(define-key *default-keymap* (alt #\I) undefined-command)
1651 ;;(define-key *default-keymap* (alt #\J) undefined-command)
1652 ;;(define-key *default-keymap* (alt #\K) undefined-command)
1653 ;;(define-key *default-keymap* (alt #\L) undefined-command)
1654 ;;(define-key *default-keymap* (alt #\M) undefined-command)
1655 ;;(define-key *default-keymap* (alt #\N) undefined-command)
1656 ;;(define-key *default-keymap* (alt #\O) undefined-command)
1657 ;;(define-key *default-keymap* (alt #\P) undefined-command)
1658 ;;(define-key *default-keymap* (alt #\Q) undefined-command)
1659 ;;(define-key *default-keymap* (alt #\R) undefined-command)
1660 ;;(define-key *default-keymap* (alt #\S) undefined-command)
1661 ;;(define-key *default-keymap* (alt #\T) undefined-command)
1662 ;;(define-key *default-keymap* (alt #\U) undefined-command)
1663 ;;(define-key *default-keymap* (alt #\V) undefined-command)
1664 ;;(define-key *default-keymap* (alt #\W) undefined-command)
1665 ;;(define-key *default-keymap* (alt #\X) undefined-command)
1666 (define-key *default-keymap* (alt #\Y) yank-pop)
1667 ;;(define-key *default-keymap* (alt #\Z) undefined-command)
1668 ;;(define-key *default-keymap* (alt #\[) undefined-command)
1669 ;;(define-key *default-keymap* (alt #\\) undefined-command)
1670 ;;(define-key *default-keymap* (alt #\]) undefined-command)
1671 ;;(define-key *default-keymap* (alt #\^) undefined-command)
1672 ;;(define-key *default-keymap* (alt #\_) undefined-command)
1673
1674 ;;(define-key *default-keymap* (alt #\`) undefined-command)
1675 ;;(define-key *default-keymap* (alt #\a) undefined-command)
1676 (define-key *default-keymap* (alt #\b) backward-word)
1677 ;;(define-key *default-keymap* (alt #\c) undefined-command)
1678 (define-key *default-keymap* (alt #\d) kill-word)
1679 ;;(define-key *default-keymap* (alt #\e) undefined-command)
1680 (define-key *default-keymap* (alt #\f) forward-word)
1681 ;;(define-key *default-keymap* (alt #\g) undefined-command)
1682 (define-key *default-keymap* (alt #\h) *help-keymap*)
1683 ;;(define-key *default-keymap* (alt #\i) undefined-command)
1684 ;;(define-key *default-keymap* (alt #\j) undefined-command)
1685 ;;(define-key *default-keymap* (alt #\k) undefined-command)
1686 ;;(define-key *default-keymap* (alt #\l) undefined-command)
1687 ;;(define-key *default-keymap* (alt #\m) undefined-command)
1688 (define-key *default-keymap* (alt #\n) next-history)
1689 ;;(define-key *default-keymap* (alt #\o) undefined-command)
1690 (define-key *default-keymap* (alt #\p) prev-history)
1691 ;;(define-key *default-keymap* (alt #\q) undefined-command)
1692 ;;(define-key *default-keymap* (alt #\r) undefined-command)
1693 ;;(define-key *default-keymap* (alt #\s) undefined-command)
1694 ;;(define-key *default-keymap* (alt #\t) undefined-command)
1695 ;;(define-key *default-keymap* (alt #\u) undefined-command)
1696 ;;(define-key *default-keymap* (alt #\v) undefined-command)
1697 (define-key *default-keymap* (alt #\w) kill-ring-save)
1698 ;;(define-key *default-keymap* (alt #\x) undefined-command)
1699 (define-key *default-keymap* (alt #\y) yank-pop)
1700 ;;(define-key *default-keymap* (alt #\z) undefined-command)
1701 ;;(define-key *default-keymap* (alt #\{) undefined-command)
1702 ;;(define-key *default-keymap* (alt #\|) undefined-command)
1703 ;;(define-key *default-keymap* (alt #\}) undefined-command)
1704 ;;(define-key *default-keymap* (alt #\)) undefined-command)
1705 ;;(define-key *default-keymap* (alt #\_) undefined-command)
1706 (define-key *default-keymap* (alt #\x7f) backward-kill-word)
1707
1708 (define-key *default-keymap* #\x7f delete-backward-char)
1709
1710 ;;(define-key *default-keymap* (alt (ctrl #\space)) undefined-command)
1711 ;;(define-key *default-keymap* (alt (ctrl #\a)) undefined-command)
1712 ;;(define-key *default-keymap* (alt (ctrl #\b)) undefined-command)
1713 ;;(define-key *default-keymap* (alt (ctrl #\c)) undefined-command)
1714 ;;(define-key *default-keymap* (alt (ctrl #\d)) undefined-command)
1715 ;;(define-key *default-keymap* (alt (ctrl #\e)) undefined-command)
1716 ;;(define-key *default-keymap* (alt (ctrl #\f)) undefined-command)
1717 ;;(define-key *default-keymap* (alt (ctrl #\g)) undefined-command)
1718 ;;(define-key *default-keymap* (alt (ctrl #\h)) undefined-command)
1719 ;;(define-key *default-keymap* (alt (ctrl #\i)) undefined-command)
1720 ;;(define-key *default-keymap* (alt (ctrl #\j)) undefined-command)
1721 ;;(define-key *default-keymap* (alt (ctrl #\k)) undefined-command)
1722 ;;(define-key *default-keymap* (alt (ctrl #\l)) undefined-command)
1723 ;;(define-key *default-keymap* (alt (ctrl #\m)) undefined-command)
1724 ;;(define-key *default-keymap* (alt (ctrl #\n)) undefined-command)
1725 ;;(define-key *default-keymap* (alt (ctrl #\o)) undefined-command)
1726 ;;(define-key *default-keymap* (alt (ctrl #\p)) undefined-command)
1727 ;;(define-key *default-keymap* (alt (ctrl #\q)) undefined-command)
1728 ;;(define-key *default-keymap* (alt (ctrl #\r)) undefined-command)
1729 ;;(define-key *default-keymap* (alt (ctrl #\s)) undefined-command)
1730 ;;(define-key *default-keymap* (alt (ctrl #\t)) undefined-command)
1731 ;;(define-key *default-keymap* (alt (ctrl #\u)) undefined-command)
1732 ;;(define-key *default-keymap* (alt (ctrl #\v)) undefined-command)
1733 ;;(define-key *default-keymap* (alt (ctrl #\w)) undefined-command)
1734 (define-key *default-keymap* (alt (ctrl #\x)) commit-input)
1735 ;;(define-key *default-keymap* (alt (ctrl #\y)) undefined-command)
1736 ;;(define-key *default-keymap* (alt (ctrl #\z)) undefined-command)
1737 ;;(define-key *default-keymap* (alt (ctrl #\[)) undefined-command)
1738 ;;(define-key *default-keymap* (alt (ctrl #\\)) undefined-command)
1739 ;;(define-key *default-keymap* (alt (ctrl #\])) undefined-command)
1740 ;;(define-key *default-keymap* (alt (ctrl #\^)) undefined-command)
1741 ;;(define-key *default-keymap* (alt (ctrl #\_)) undefined-command)
1742
1743 (define-key *default-keymap* 'KEY_UP prev-line-or-history)
1744 (define-key *default-keymap* 'KEY_DOWN next-line-or-history)
1745 (define-key *default-keymap* 'KEY_LEFT backward-char)
1746 (define-key *default-keymap* 'KEY_RIGHT forward-char)
1747 ;;(define-key *default-keymap* 'KEY_INS ,undefined-command)
1748 (define-key *default-keymap* 'KEY_DEL delete-char)
1749 ;;(define-key *default-keymap* 'KEY_HOME undefined-command)
1750 ;;(define-key *default-keymap* 'KEY_END ,undefined-command)
1751 ;;(define-key *default-keymap* 'KEY_PGDN undefined-command)
1752 ;;(define-key *default-keymap* 'KEY_PGUP undefined-command)
1753 ;;(define-key *default-keymap* 'KEY_F1 ,undefined-command)
1754 ;;(define-key *default-keymap* 'KEY_F2 ,undefined-command)
1755 ;;(define-key *default-keymap* 'KEY_F3 ,undefined-command)
1756 ;;(define-key *default-keymap* 'KEY_F4 ,undefined-command)
1757 ;;(define-key *default-keymap* 'KEY_F5 ,undefined-command)
1758 ;;(define-key *default-keymap* 'KEY_F6 ,undefined-command)
1759 ;;(define-key *default-keymap* 'KEY_F7 ,undefined-command)
1760 ;;(define-key *default-keymap* 'KEY_F8 ,undefined-command)
1761 ;;(define-key *default-keymap* 'KEY_F9 ,undefined-command)
1762 ;;(define-key *default-keymap* 'KEY_F10 ,undefined-command)
1763 ;;(define-key *default-keymap* 'KEY_F11 ,undefined-command)
1764 ;;(define-key *default-keymap* 'KEY_F12 ,undefined-command)
1765
1766 ;; external api
1767 (define (default-keymap) *default-keymap*)
1768
1769 #|
1770
1771 Undo semantics
1772
1773 We emulate Emacs undo semantics, which allows "undoing undo".
1774 Here's the description of algorithm.
1775
1776 - A, B, C, ... is an edit commans
1777 - Applying command A to buffer v is v*A.
1778 - ^X is an inversion of command X. X*^X = ^X*X = I (identity)
1779
1780 1. Suppose the user did three buffer-changing operations, A, B and C.
1781 For every such operation, we push "undo procedure" into undo-stack.
1782 If we write undo procedure of A as ^A, the undo stack would look
1783 like this:
1784
1785 buffer: v*A*B*C
1786 undo stack: ^A ^B ^C
1787 redo queue:
1788
1789 2. If the user invoke undo command, we pop one undo procedure and applies
1790 to the buffer, then (1) append the undo op to the front of redo queue,
1791 and (2) push the redo op to the rear of redo queue.
1792
1793 buffer: v*A*B
1794 undo stack: ^A ^B
1795 redo queue: ^C C
1796
1797 3. If the user invoke undo command again immediately after that (that is,
1798 the user does not do any operation, including cursor movement),
1799 we keep doing the same op.
1800
1801 buffer: v*A
1802 undo stack: ^A
1803 redo queue: ^B ^C C B
1804
1805 4. If the user does anything but undo command here, we flush the redo queue
1806 and append the contents to undo stack.
1807
1808 buffer: v*A
1809 undo stack: ^A ^B ^C C B
1810 redo queue:
1811
1812 5. If the user does undo again, it actually redoes the last undo.
1813
1814 buffer: v*A*B
1815 undo stack: ^A ^B ^C C
1816 redo queue: B ^B
1817
1818 6. Contiguous undo follows the same pattern, until the undo stack get
1819 empty.
1820
1821 buffer: v*A*B*C
1822 undo stack:
1823 redo queue: ^A ^B ^C C B ^B ^C C B A
1824 |#