Free the debug info when making a critical section global.
[wine] / dlls / kernel / editline.c
1 /*
2  * line edition function for Win32 console
3  *
4  * Copyright 2001 Eric Pouech
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <string.h>
25
26 #include "windef.h"
27 #include "winbase.h"
28 #include "wincon.h"
29 #include "wine/unicode.h"
30 #include "winnls.h"
31 #include "wine/debug.h"
32 #include "console_private.h"
33
34 WINE_DEFAULT_DEBUG_CHANNEL(console);
35
36 struct WCEL_Context;
37
38 typedef struct
39 {
40     WCHAR                       val;            /* vk or unicode char */
41     void                        (*func)(struct WCEL_Context* ctx);
42 } KeyEntry;
43
44 typedef struct
45 {
46     DWORD                       keyState;       /* keyState (from INPUT_RECORD) to match */
47     BOOL                        chkChar;        /* check vk or char */
48     KeyEntry*                   entries;        /* array of entries */
49 } KeyMap;
50
51 typedef struct WCEL_Context {
52     WCHAR*                      line;           /* the line being edited */
53     size_t                      alloc;          /* number of WCHAR in line */
54     unsigned                    len;            /* number of chars in line */
55     unsigned                    ofs;            /* offset for cursor in current line */
56     WCHAR*                      yanked;         /* yanked line */
57     unsigned                    mark;           /* marked point (emacs mode only) */
58     CONSOLE_SCREEN_BUFFER_INFO  csbi;           /* current state (initial cursor, window size, attribute) */
59     HANDLE                      hConIn;
60     HANDLE                      hConOut;
61     unsigned                    done : 1,       /* to 1 when we're done with editing */
62                                 error : 1,      /* to 1 when an error occurred in the editing */
63                                 can_wrap : 1;   /* to 1 when multi-line edition can take place */
64     unsigned                    histSize;
65     unsigned                    histPos;
66     WCHAR*                      histCurr;
67 } WCEL_Context;
68
69 #if 0
70 static void WCEL_Dump(WCEL_Context* ctx, const char* pfx)
71 {
72     MESSAGE("%s: [line=%s[alloc=%u] ofs=%u len=%u start=(%d,%d) mask=%c%c%c]\n"
73             "\t\thist=(size=%u pos=%u curr=%s)\n"
74             "\t\tyanked=%s\n",
75             pfx, debugstr_w(ctx->line), ctx->alloc, ctx->ofs, ctx->len,
76             ctx->csbi.dwCursorPosition.X, ctx->csbi.dwCursorPosition.Y,
77             ctx->done ? 'D' : 'd', ctx->error ? 'E' : 'e', ctx->can_wrap ? 'W' : 'w',
78             ctx->histSize, ctx->histPos, debugstr_w(ctx->histCurr),
79             debugstr_w(ctx->yanked));
80 }
81 #endif
82
83 /* ====================================================================
84  *
85  * Console helper functions
86  *
87  * ====================================================================*/
88
89 static BOOL WCEL_Get(WCEL_Context* ctx, INPUT_RECORD* ir)
90 {
91     if (ReadConsoleInputW(ctx->hConIn, ir, 1, NULL)) return TRUE;
92     ERR("hmm bad situation\n");
93     ctx->error = 1;
94     return FALSE;
95 }
96
97 static inline void WCEL_Beep(WCEL_Context* ctx)
98 {
99     Beep(400, 300);
100 }
101
102 static inline BOOL WCEL_IsSingleLine(WCEL_Context* ctx, size_t len)
103 {
104     return ctx->csbi.dwCursorPosition.X + ctx->len + len <= ctx->csbi.dwSize.X;
105 }
106
107 static inline COORD WCEL_GetCoord(WCEL_Context* ctx, int ofs)
108 {
109     COORD       c;
110     unsigned    len = ctx->csbi.dwSize.X - ctx->csbi.dwCursorPosition.X;
111
112     c.Y = ctx->csbi.dwCursorPosition.Y;
113     if (ofs >= len)
114     {
115         ofs -= len;
116         c.X = ofs % ctx->csbi.dwSize.X;
117         c.Y += 1 + ofs / ctx->csbi.dwSize.X;
118     }
119     else c.X = ctx->csbi.dwCursorPosition.X + ofs;
120     return c;
121 }
122
123 static inline void WCEL_Update(WCEL_Context* ctx, int beg, int len)
124 {
125     WriteConsoleOutputCharacterW(ctx->hConOut, &ctx->line[beg], len,
126                                  WCEL_GetCoord(ctx, beg), NULL);
127     FillConsoleOutputAttribute(ctx->hConOut, ctx->csbi.wAttributes, len,
128                                WCEL_GetCoord(ctx, beg), NULL);
129 }
130
131 /* ====================================================================
132  *
133  * context manipulation functions
134  *
135  * ====================================================================*/
136
137 static BOOL WCEL_Grow(WCEL_Context* ctx, size_t len)
138 {
139     if (!WCEL_IsSingleLine(ctx, len) && !ctx->can_wrap)
140     {
141         FIXME("Mode doesn't allow to wrap. However, we should allow to overwrite current string\n");
142         return FALSE;
143     }
144
145     if (ctx->len + len >= ctx->alloc)
146     {
147         WCHAR*  newline;
148         size_t  newsize;
149
150         /* round up size to 32 byte-WCHAR boundary */
151         newsize = (ctx->len + len + 1 + 31) & ~31;
152         newline = HeapReAlloc(GetProcessHeap(), 0, ctx->line, sizeof(WCHAR) * newsize);
153         if (!newline) return FALSE;
154         ctx->line = newline;
155         ctx->alloc = newsize;
156     }
157     return TRUE;
158 }
159
160 static void WCEL_DeleteString(WCEL_Context* ctx, int beg, int end)
161 {
162     unsigned    str_len = end - beg;
163     COORD       cbeg = WCEL_GetCoord(ctx, ctx->len - str_len);
164     COORD       cend = WCEL_GetCoord(ctx, ctx->len);
165     CHAR_INFO   ci;
166
167     if (end < ctx->len)
168         memmove(&ctx->line[beg], &ctx->line[end], (ctx->len - end) * sizeof(WCHAR));
169     /* we need to clean from ctx->len - str_len to ctx->len */
170
171     ci.Char.UnicodeChar = ' ';
172     ci.Attributes = ctx->csbi.wAttributes;
173
174     if (cbeg.Y == cend.Y)
175     {
176         /* partial erase of sole line */
177         CONSOLE_FillLineUniform(ctx->hConOut, cbeg.X, cbeg.Y,
178                                 cend.X - cbeg.X, &ci);
179     }
180     else
181     {
182         int         i;
183         /* erase til eol on first line */
184         CONSOLE_FillLineUniform(ctx->hConOut, cbeg.X, cbeg.Y,
185                                 ctx->csbi.dwSize.X - cbeg.X, &ci);
186         /* completly erase all the others (full lines) */
187         for (i = cbeg.Y + 1; i < cend.Y; i++)
188             CONSOLE_FillLineUniform(ctx->hConOut, 0, i, ctx->csbi.dwSize.X, &ci);
189         /* erase from beg of line until last pos on last line */
190         CONSOLE_FillLineUniform(ctx->hConOut, 0, cend.Y, cend.X, &ci);
191     }
192     ctx->len -= str_len;
193     WCEL_Update(ctx, 0, ctx->len);
194     ctx->line[ctx->len] = 0;
195 }
196
197 static void WCEL_InsertString(WCEL_Context* ctx, const WCHAR* str)
198 {
199     size_t      len = lstrlenW(str);
200
201     if (!len || !WCEL_Grow(ctx, len)) return;
202     if (ctx->len > ctx->ofs)
203         memmove(&ctx->line[ctx->ofs + len], &ctx->line[ctx->ofs], (ctx->len - ctx->ofs) * sizeof(WCHAR));
204     memcpy(&ctx->line[ctx->ofs], str, len * sizeof(WCHAR));
205     ctx->len += len;
206     ctx->line[ctx->len] = 0;
207     WCEL_Update(ctx, ctx->ofs, ctx->len - ctx->ofs);
208
209     ctx->ofs += len;
210 }
211
212 static void WCEL_InsertChar(WCEL_Context* ctx, WCHAR c)
213 {
214     WCHAR       buffer[2];
215
216     /* do not insert 0..31 control characters */
217     if (c < ' ' && c != '\t') return;
218
219     buffer[0] = c;
220     buffer[1] = 0;
221     WCEL_InsertString(ctx, buffer);
222 }
223
224 static void WCEL_FreeYank(WCEL_Context* ctx)
225 {
226     if (ctx->yanked)
227     {
228         HeapFree(GetProcessHeap(), 0, ctx->yanked);
229         ctx->yanked = NULL;
230     }
231 }
232
233 static void WCEL_SaveYank(WCEL_Context* ctx, int beg, int end)
234 {
235     int len = end - beg;
236     if (len <= 0) return;
237
238     WCEL_FreeYank(ctx);
239     ctx->yanked = HeapReAlloc(GetProcessHeap(), 0, ctx->yanked, (len + 1) * sizeof(WCHAR));
240     if (!ctx->yanked) return;
241     memcpy(ctx->yanked, &ctx->line[beg], len * sizeof(WCHAR));
242     ctx->yanked[len] = 0;
243 }
244
245 /* FIXME NTDLL doesn't export iswalnum, and I don't want to link in msvcrt when most
246  * of the data lay in unicode lib
247  */
248 static inline BOOL WCEL_iswalnum(WCHAR wc)
249 {
250     return get_char_typeW(wc) & (C1_ALPHA|C1_DIGIT|C1_LOWER|C1_UPPER);
251 }
252
253 static int WCEL_GetLeftWordTransition(WCEL_Context* ctx, int ofs)
254 {
255     ofs--;
256     while (ofs >= 0 && !WCEL_iswalnum(ctx->line[ofs])) ofs--;
257     while (ofs >= 0 && WCEL_iswalnum(ctx->line[ofs])) ofs--;
258     if (ofs >= 0) ofs++;
259     return max(ofs, 0);
260 }
261
262 static int WCEL_GetRightWordTransition(WCEL_Context* ctx, int ofs)
263 {
264     ofs++;
265     while (ofs <= ctx->len && WCEL_iswalnum(ctx->line[ofs])) ofs++;
266     while (ofs <= ctx->len && !WCEL_iswalnum(ctx->line[ofs])) ofs++;
267     return min(ofs, ctx->len);
268 }
269
270 static WCHAR* WCEL_GetHistory(WCEL_Context* ctx, int idx)
271 {
272     WCHAR*      ptr;
273
274     if (idx == ctx->histSize - 1)
275     {
276         ptr = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(ctx->histCurr) + 1) * sizeof(WCHAR));
277         lstrcpyW(ptr, ctx->histCurr);
278     }
279     else
280     {
281         int     len = CONSOLE_GetHistory(idx, NULL, 0);
282
283         if ((ptr = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR))))
284         {
285             CONSOLE_GetHistory(idx, ptr, len);
286         }
287     }
288     return ptr;
289 }
290
291 static void     WCEL_HistoryInit(WCEL_Context* ctx)
292 {
293     ctx->histPos  = CONSOLE_GetNumHistoryEntries();
294     ctx->histSize = ctx->histPos + 1;
295     ctx->histCurr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WCHAR));
296 }
297
298 static void    WCEL_MoveToHist(WCEL_Context* ctx, int idx)
299 {
300     WCHAR*      data = WCEL_GetHistory(ctx, idx);
301     int         len = lstrlenW(data) + 1;
302
303     /* save current line edition for recall when needed (FIXME seems broken to me) */
304     if (ctx->histPos == ctx->histSize - 1)
305     {
306         if (ctx->histCurr) HeapFree(GetProcessHeap(), 0, ctx->histCurr);
307         ctx->histCurr = HeapAlloc(GetProcessHeap(), 0, (ctx->len + 1) * sizeof(WCHAR));
308         memcpy(ctx->histCurr, ctx->line, (ctx->len + 1) * sizeof(WCHAR));
309     }
310     /* need to clean also the screen if new string is shorter than old one */
311     WCEL_DeleteString(ctx, 0, ctx->len);
312     ctx->ofs = 0;
313     /* insert new string */
314     if (WCEL_Grow(ctx, len))
315     {
316         WCEL_InsertString(ctx, data);
317         HeapFree(GetProcessHeap(), 0, data);
318         ctx->histPos = idx;
319     }
320 }
321
322 static void    WCEL_FindPrevInHist(WCEL_Context* ctx)
323 {
324     int startPos = ctx->histPos;
325     WCHAR*      data;
326     int         len, oldofs;
327
328     if (ctx->histPos && ctx->histPos == ctx->histSize) {
329         startPos--;
330         ctx->histPos--;
331     }
332
333     do {
334        data = WCEL_GetHistory(ctx, ctx->histPos);
335
336        if (ctx->histPos) ctx->histPos--;
337        else ctx->histPos = (ctx->histSize-1);
338
339        len = lstrlenW(data) + 1;
340        if ((len >= ctx->ofs) &&
341            (memcmp(ctx->line, data, ctx->ofs * sizeof(WCHAR)) == 0)) {
342
343            /* need to clean also the screen if new string is shorter than old one */
344            WCEL_DeleteString(ctx, 0, ctx->len);
345
346            if (WCEL_Grow(ctx, len))
347            {
348               oldofs = ctx->ofs;
349               ctx->ofs = 0;
350               WCEL_InsertString(ctx, data);
351               ctx->ofs = oldofs;
352               SetConsoleCursorPosition(ctx->hConOut, WCEL_GetCoord(ctx, ctx->ofs));
353               HeapFree(GetProcessHeap(), 0, data);
354               return;
355            }
356        }
357     } while (ctx->histPos != startPos);
358
359     return;
360 }
361
362 /* ====================================================================
363  *
364  * basic edition functions
365  *
366  * ====================================================================*/
367
368 static void WCEL_Done(WCEL_Context* ctx)
369 {
370     WCHAR       nl = '\n';
371     if (!WCEL_Grow(ctx, 1)) return;
372     ctx->line[ctx->len++] = '\n';
373     ctx->line[ctx->len] = 0;
374     WriteConsoleW(ctx->hConOut, &nl, 1, NULL, NULL);
375     ctx->done = 1;
376 }
377
378 static void WCEL_MoveLeft(WCEL_Context* ctx)
379 {
380     if (ctx->ofs > 0) ctx->ofs--;
381 }
382
383 static void WCEL_MoveRight(WCEL_Context* ctx)
384 {
385     if (ctx->ofs < ctx->len) ctx->ofs++;
386 }
387
388 static void WCEL_MoveToLeftWord(WCEL_Context* ctx)
389 {
390     int new_ofs = WCEL_GetLeftWordTransition(ctx, ctx->ofs);
391     if (new_ofs != ctx->ofs) ctx->ofs = new_ofs;
392 }
393
394 static void WCEL_MoveToRightWord(WCEL_Context* ctx)
395 {
396     int new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
397     if (new_ofs != ctx->ofs) ctx->ofs = new_ofs;
398 }
399
400 static void WCEL_MoveToBeg(WCEL_Context* ctx)
401 {
402     ctx->ofs = 0;
403 }
404
405 static void WCEL_MoveToEnd(WCEL_Context* ctx)
406 {
407     ctx->ofs = ctx->len;
408 }
409
410 static void WCEL_SetMark(WCEL_Context* ctx)
411 {
412     ctx->mark = ctx->ofs;
413 }
414
415 static void WCEL_ExchangeMark(WCEL_Context* ctx)
416 {
417     unsigned tmp;
418
419     if (ctx->mark > ctx->len) return;
420     tmp = ctx->ofs;
421     ctx->ofs = ctx->mark;
422     ctx->mark = tmp;
423 }
424
425 static void WCEL_CopyMarkedZone(WCEL_Context* ctx)
426 {
427     unsigned beg, end;
428
429     if (ctx->mark > ctx->len || ctx->mark == ctx->ofs) return;
430     if (ctx->mark > ctx->ofs)
431     {
432         beg = ctx->ofs;         end = ctx->mark;
433     }
434     else
435     {
436         beg = ctx->mark;        end = ctx->ofs;
437     }
438     WCEL_SaveYank(ctx, beg, end);
439 }
440
441 static void WCEL_TransposeChar(WCEL_Context* ctx)
442 {
443     WCHAR       c;
444
445     if (!ctx->ofs || ctx->ofs == ctx->len) return;
446
447     c = ctx->line[ctx->ofs];
448     ctx->line[ctx->ofs] = ctx->line[ctx->ofs - 1];
449     ctx->line[ctx->ofs - 1] = c;
450
451     WCEL_Update(ctx, ctx->ofs - 1, 2);
452     ctx->ofs++;
453 }
454
455 static void WCEL_TransposeWords(WCEL_Context* ctx)
456 {
457     int left_ofs = WCEL_GetLeftWordTransition(ctx, ctx->ofs),
458         right_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
459     if (left_ofs < ctx->ofs && right_ofs > ctx->ofs)
460     {
461         unsigned len_r = right_ofs - ctx->ofs;
462         unsigned len_l = ctx->ofs - left_ofs;
463
464         char*   tmp = HeapAlloc(GetProcessHeap(), 0, len_r * sizeof(WCHAR));
465         if (!tmp) return;
466
467         memcpy(tmp, &ctx->line[ctx->ofs], len_r * sizeof(WCHAR));
468         memmove(&ctx->line[left_ofs + len_r], &ctx->line[left_ofs], len_l * sizeof(WCHAR));
469         memcpy(&ctx->line[left_ofs], tmp, len_r * sizeof(WCHAR));
470
471         HeapFree(GetProcessHeap(), 0, tmp);
472         WCEL_Update(ctx, left_ofs, len_l + len_r);
473         ctx->ofs = right_ofs;
474     }
475 }
476
477 static void WCEL_LowerCaseWord(WCEL_Context* ctx)
478 {
479     int new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
480     if (new_ofs != ctx->ofs)
481     {
482         int     i;
483         for (i = ctx->ofs; i <= new_ofs; i++)
484             ctx->line[i] = tolowerW(ctx->line[i]);
485         WCEL_Update(ctx, ctx->ofs, new_ofs - ctx->ofs + 1);
486         ctx->ofs = new_ofs;
487     }
488 }
489
490 static void WCEL_UpperCaseWord(WCEL_Context* ctx)
491 {
492     int new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
493     if (new_ofs != ctx->ofs)
494     {
495         int     i;
496         for (i = ctx->ofs; i <= new_ofs; i++)
497             ctx->line[i] = toupperW(ctx->line[i]);
498         WCEL_Update(ctx, ctx->ofs, new_ofs - ctx->ofs + 1);
499         ctx->ofs = new_ofs;
500     }
501 }
502
503 static void WCEL_CapitalizeWord(WCEL_Context* ctx)
504 {
505     int new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
506     if (new_ofs != ctx->ofs)
507     {
508         int     i;
509
510         ctx->line[ctx->ofs] = toupperW(ctx->line[ctx->ofs]);
511         for (i = ctx->ofs + 1; i <= new_ofs; i++)
512             ctx->line[i] = tolowerW(ctx->line[i]);
513         WCEL_Update(ctx, ctx->ofs, new_ofs - ctx->ofs + 1);
514         ctx->ofs = new_ofs;
515     }
516 }
517
518 static void WCEL_Yank(WCEL_Context* ctx)
519 {
520     WCEL_InsertString(ctx, ctx->yanked);
521 }
522
523 static void WCEL_KillToEndOfLine(WCEL_Context* ctx)
524 {
525     WCEL_SaveYank(ctx, ctx->ofs, ctx->len);
526     WCEL_DeleteString(ctx, ctx->ofs, ctx->len);
527 }
528
529 static void WCEL_KillMarkedZone(WCEL_Context* ctx)
530 {
531     unsigned beg, end;
532
533     if (ctx->mark > ctx->len || ctx->mark == ctx->ofs) return;
534     if (ctx->mark > ctx->ofs)
535     {
536         beg = ctx->ofs;         end = ctx->mark;
537     }
538     else
539     {
540         beg = ctx->mark;        end = ctx->ofs;
541     }
542     WCEL_SaveYank(ctx, beg, end);
543     WCEL_DeleteString(ctx, beg, end);
544     ctx->ofs = beg;
545 }
546
547 static void WCEL_DeletePrevChar(WCEL_Context* ctx)
548 {
549     if (ctx->ofs)
550     {
551         WCEL_DeleteString(ctx, ctx->ofs - 1, ctx->ofs);
552         ctx->ofs--;
553     }
554 }
555
556 static void WCEL_DeleteCurrChar(WCEL_Context* ctx)
557 {
558     if (ctx->ofs < ctx->len)
559         WCEL_DeleteString(ctx, ctx->ofs, ctx->ofs + 1);
560 }
561
562 static void WCEL_DeleteLeftWord(WCEL_Context* ctx)
563 {
564     int new_ofs = WCEL_GetLeftWordTransition(ctx, ctx->ofs);
565     if (new_ofs != ctx->ofs)
566     {
567         WCEL_DeleteString(ctx, new_ofs, ctx->ofs);
568         ctx->ofs = new_ofs;
569     }
570 }
571
572 static void WCEL_DeleteRightWord(WCEL_Context* ctx)
573 {
574     int new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
575     if (new_ofs != ctx->ofs)
576     {
577         WCEL_DeleteString(ctx, ctx->ofs, new_ofs);
578     }
579 }
580
581 static void WCEL_MoveToPrevHist(WCEL_Context* ctx)
582 {
583     if (ctx->histPos) WCEL_MoveToHist(ctx, ctx->histPos - 1);
584 }
585
586 static void WCEL_MoveToNextHist(WCEL_Context* ctx)
587 {
588     if (ctx->histPos < ctx->histSize - 1) WCEL_MoveToHist(ctx, ctx->histPos + 1);
589 }
590
591 static void WCEL_MoveToFirstHist(WCEL_Context* ctx)
592 {
593     if (ctx->histPos != 0) WCEL_MoveToHist(ctx, 0);
594 }
595
596 static void WCEL_MoveToLastHist(WCEL_Context* ctx)
597 {
598     if (ctx->histPos != ctx->histSize - 1) WCEL_MoveToHist(ctx, ctx->histSize - 1);
599 }
600
601 static void WCEL_Redraw(WCEL_Context* ctx)
602 {
603     COORD       c = WCEL_GetCoord(ctx, ctx->len);
604     CHAR_INFO   ci;
605
606     WCEL_Update(ctx, 0, ctx->len);
607
608     ci.Char.UnicodeChar = ' ';
609     ci.Attributes = ctx->csbi.wAttributes;
610
611     CONSOLE_FillLineUniform(ctx->hConOut, c.X, c.Y, ctx->csbi.dwSize.X - c.X, &ci);
612 }
613
614 static void WCEL_RepeatCount(WCEL_Context* ctx)
615 {
616 #if 0
617 /* FIXME: wait until all console code is in kernel32 */
618     INPUT_RECORD        ir;
619     unsigned            repeat = 0;
620
621     while (WCEL_Get(ctx, &ir, FALSE))
622     {
623         if (ir.EventType != KEY_EVENT) break;
624         if (ir.Event.KeyEvent.bKeyDown)
625         {
626             if ((ir.Event.KeyEvent.dwControlKeyState & ~(NUMLOCK_ON|SCROLLLOCK_ON|CAPSLOCK_ON)) != 0)
627                 break;
628             if (ir.Event.KeyEvent.uChar.UnicodeChar < '0' ||
629                 ir.Event.KeyEvent.uChar.UnicodeChar > '9')
630                 break;
631             repeat = repeat * 10 + ir.Event.KeyEvent.uChar.UnicodeChar - '0';
632         }
633         WCEL_Get(ctx, &ir, TRUE);
634     }
635     FIXME("=> %u\n", repeat);
636 #endif
637 }
638
639 /* ====================================================================
640  *
641  *              Key Maps
642  *
643  * ====================================================================*/
644
645 #define CTRL(x) ((x) - '@')
646 static KeyEntry StdKeyMap[] =
647 {
648     {/*BACK*/0x08,      WCEL_DeletePrevChar     },
649     {/*RETURN*/0x0d,    WCEL_Done               },
650     {/*DEL*/127,        WCEL_DeleteCurrChar     },
651     {   0,              NULL                    }
652 };
653
654 static KeyEntry Win32ExtraStdKeyMap[] =
655 {
656     {/*VK_F8*/   0x77,  WCEL_FindPrevInHist     },
657     {   0,              NULL                    }
658 };
659
660
661 static  KeyEntry EmacsKeyMapCtrl[] =
662 {
663     {   CTRL('@'),      WCEL_SetMark            },
664     {   CTRL('A'),      WCEL_MoveToBeg          },
665     {   CTRL('B'),      WCEL_MoveLeft           },
666     /* C: done in server */
667     {   CTRL('D'),      WCEL_DeleteCurrChar     },
668     {   CTRL('E'),      WCEL_MoveToEnd          },
669     {   CTRL('F'),      WCEL_MoveRight          },
670     {   CTRL('G'),      WCEL_Beep               },
671     {   CTRL('H'),      WCEL_DeletePrevChar     },
672     /* I: meaningless (or tab ???) */
673     {   CTRL('J'),      WCEL_Done               },
674     {   CTRL('K'),      WCEL_KillToEndOfLine    },
675     {   CTRL('L'),      WCEL_Redraw             },
676     {   CTRL('M'),      WCEL_Done               },
677     {   CTRL('N'),      WCEL_MoveToNextHist     },
678     /* O; insert line... meaningless */
679     {   CTRL('P'),      WCEL_MoveToPrevHist     },
680     /* Q: [NIY] quoting... */
681     /* R: [NIY] search backwards... */
682     /* S: [NIY] search forwards... */
683     {   CTRL('T'),      WCEL_TransposeChar      },
684     {   CTRL('U'),      WCEL_RepeatCount        },
685     /* V: paragraph down... meaningless */
686     {   CTRL('W'),      WCEL_KillMarkedZone     },
687     {   CTRL('X'),      WCEL_ExchangeMark       },
688     {   CTRL('Y'),      WCEL_Yank               },
689     /* Z: meaningless */
690     {   0,              NULL                    }
691 };
692
693 static KeyEntry EmacsKeyMapAlt[] =
694 {
695     {/*DEL*/127,        WCEL_DeleteLeftWord     },
696     {   '<',            WCEL_MoveToFirstHist    },
697     {   '>',            WCEL_MoveToLastHist     },
698     {   '?',            WCEL_Beep               },
699     {   'b',            WCEL_MoveToLeftWord     },
700     {   'c',            WCEL_CapitalizeWord     },
701     {   'd',            WCEL_DeleteRightWord    },
702     {   'f',            WCEL_MoveToRightWord    },
703     {   'l',            WCEL_LowerCaseWord      },
704     {   't',            WCEL_TransposeWords     },
705     {   'u',            WCEL_UpperCaseWord      },
706     {   'w',            WCEL_CopyMarkedZone     },
707     {   0,              NULL                    }
708 };
709
710 static KeyEntry EmacsKeyMapExtended[] =
711 {
712     {/*RETURN*/  0x0d,  WCEL_Done },
713     {/*VK_PRIOR*/0x21,  WCEL_MoveToPrevHist     },
714     {/*VK_NEXT*/ 0x22,  WCEL_MoveToNextHist     },
715     {/*VK_END*/  0x23,  WCEL_MoveToEnd          },
716     {/*VK_HOME*/ 0x24,  WCEL_MoveToBeg          },
717     {/*VK_RIGHT*/0x27,  WCEL_MoveRight          },
718     {/*VK_LEFT*/ 0x25,  WCEL_MoveLeft           },
719     {/*VK_DEL*/  0x2e,  WCEL_DeleteCurrChar     },
720     {   0,              NULL                    }
721 };
722
723 static KeyMap   EmacsKeyMap[] =
724 {
725     {0x00000000, 1, StdKeyMap},
726     {0x00000001, 1, EmacsKeyMapAlt},    /* left  alt  */
727     {0x00000002, 1, EmacsKeyMapAlt},    /* right alt  */
728     {0x00000004, 1, EmacsKeyMapCtrl},   /* left  ctrl */
729     {0x00000008, 1, EmacsKeyMapCtrl},   /* right ctrl */
730     {0x00000100, 0, EmacsKeyMapExtended},
731     {0,          0, 0}
732 };
733
734 static  KeyEntry Win32KeyMapExtended[] =
735 {
736     {/*VK_LEFT*/ 0x25,  WCEL_MoveLeft           },
737     {/*VK_RIGHT*/0x27,  WCEL_MoveRight          },
738     {/*VK_HOME*/ 0x24,  WCEL_MoveToBeg          },
739     {/*VK_END*/  0x23,  WCEL_MoveToEnd          },
740     {/*VK_UP*/   0x26,  WCEL_MoveToPrevHist     },
741     {/*VK_DOWN*/ 0x28,  WCEL_MoveToNextHist     },
742     {/*VK_DEL*/  0x2e,  WCEL_DeleteCurrChar     },
743     {   0,              NULL                    }
744 };
745
746 static  KeyEntry Win32KeyMapCtrlExtended[] =
747 {
748     {/*VK_LEFT*/ 0x25,  WCEL_MoveToLeftWord     },
749     {/*VK_RIGHT*/0x27,  WCEL_MoveToRightWord    },
750     {/*VK_END*/  0x23,  WCEL_KillToEndOfLine    },
751     {   0,              NULL                    }
752 };
753
754 KeyMap  Win32KeyMap[] =
755 {
756     {0x00000000, 1, StdKeyMap},
757     {0x00000000, 0, Win32ExtraStdKeyMap},
758     {0x00000100, 0, Win32KeyMapExtended},
759     {0x00000104, 0, Win32KeyMapCtrlExtended},
760     {0x00000108, 0, Win32KeyMapCtrlExtended},
761     {0,          0, 0}
762 };
763 #undef CTRL
764
765 /* ====================================================================
766  *
767  *              Read line master function
768  *
769  * ====================================================================*/
770
771 WCHAR* CONSOLE_Readline(HANDLE hConsoleIn)
772 {
773     WCEL_Context        ctx;
774     INPUT_RECORD        ir;
775     KeyMap*             km;
776     KeyEntry*           ke;
777     unsigned            ofs;
778     void                (*func)(struct WCEL_Context* ctx);
779     DWORD               ks;
780     int                 use_emacs;
781
782     memset(&ctx, 0, sizeof(ctx));
783     ctx.hConIn = hConsoleIn;
784     WCEL_HistoryInit(&ctx);
785
786     if (!CONSOLE_GetEditionMode(hConsoleIn, &use_emacs))
787         use_emacs = 0;
788
789     if ((ctx.hConOut = CreateFileA("CONOUT$", GENERIC_READ|GENERIC_WRITE, 0, NULL,
790                                     OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE ||
791         !GetConsoleScreenBufferInfo(ctx.hConOut, &ctx.csbi))
792         return NULL;
793     ctx.can_wrap = (GetConsoleMode(ctx.hConOut, &ks) && (ks & ENABLE_WRAP_AT_EOL_OUTPUT)) ? 1 : 0;
794
795     if (!WCEL_Grow(&ctx, 1))
796     {
797         CloseHandle(ctx.hConOut);
798         return NULL;
799     }
800     ctx.line[0] = 0;
801
802 /* EPP     WCEL_Dump(&ctx, "init"); */
803
804     while (!ctx.done && !ctx.error && WCEL_Get(&ctx, &ir))
805     {
806         if (ir.EventType != KEY_EVENT) continue;
807         TRACE("key%s repeatCount=%u, keyCode=%02x scanCode=%02x char=%02x keyState=%08lx\n",
808               ir.Event.KeyEvent.bKeyDown ? "Down" : "Up  ", ir.Event.KeyEvent.wRepeatCount,
809               ir.Event.KeyEvent.wVirtualKeyCode, ir.Event.KeyEvent.wVirtualScanCode,
810               ir.Event.KeyEvent.uChar.UnicodeChar, ir.Event.KeyEvent.dwControlKeyState);
811         if (!ir.Event.KeyEvent.bKeyDown) continue;
812
813 /* EPP          WCEL_Dump(&ctx, "before func"); */
814         ofs = ctx.ofs;
815         /* mask out some bits which don't interest us */
816         ks = ir.Event.KeyEvent.dwControlKeyState & ~(NUMLOCK_ON|SCROLLLOCK_ON|CAPSLOCK_ON);
817
818         func = NULL;
819         for (km = (use_emacs) ? EmacsKeyMap : Win32KeyMap; km->entries != NULL; km++)
820         {
821             if (km->keyState != ks)
822                 continue;
823             if (km->chkChar)
824             {
825                 for (ke = &km->entries[0]; ke->func != 0; ke++)
826                     if (ke->val == ir.Event.KeyEvent.uChar.UnicodeChar) break;
827             }
828             else
829             {
830                 for (ke = &km->entries[0]; ke->func != 0; ke++)
831                     if (ke->val == ir.Event.KeyEvent.wVirtualKeyCode) break;
832
833             }
834             if (ke->func)
835             {
836                 func = ke->func;
837                 break;
838             }
839         }
840
841         if (func)
842             (func)(&ctx);
843         else if (!(ir.Event.KeyEvent.dwControlKeyState & (ENHANCED_KEY|LEFT_ALT_PRESSED)))
844             WCEL_InsertChar(&ctx, ir.Event.KeyEvent.uChar.UnicodeChar);
845         else TRACE("Dropped event\n");
846
847 /* EPP         WCEL_Dump(&ctx, "after func"); */
848         if (ctx.ofs != ofs)
849             SetConsoleCursorPosition(ctx.hConOut, WCEL_GetCoord(&ctx, ctx.ofs));
850     }
851     if (ctx.error)
852     {
853         HeapFree(GetProcessHeap(), 0, ctx.line);
854         ctx.line = NULL;
855     }
856     WCEL_FreeYank(&ctx);
857     if (ctx.line)
858         CONSOLE_AppendHistory(ctx.line);
859
860     CloseHandle(ctx.hConOut);
861     if (ctx.histCurr) HeapFree(GetProcessHeap(), 0, ctx.histCurr);
862     return ctx.line;
863 }